使用String.split方法时要注意的问题

在使用String.split方法分隔字符串时,分隔符如果用到一些特殊字符,可能会得不到我们预期的结果。

我们看jdk doc中说明

public String[] split(String regex)

 
  Splits this string around matches of the given regular expression. 

参数regex是一个 regular-expression的匹配模式而不是一个简单的String,他对一些特殊的字符可能会出现你预想不到的结果,比如测试下面的代码:

用竖线 | 分隔字符串,你将得不到预期的结果

    String[] aa = "aaa|bbb|ccc".split("|");
    //String[] aa = "aaa|bbb|ccc".split("//|"); 这样才能得到正确的结果

    for (int i = 0 ; i <aa.length ; i++ ) {
      System.out.println("--"+aa[i]);
    }

用竖 * 分隔字符串运行将抛出java.util.regex.PatternSyntaxException异常,用加号 + 也是如此。

    String[] aa = "aaa*bbb*ccc".split("*");
    //String[] aa = "aaa|bbb|ccc".split("//*"); 这样才能得到正确的结果   

    for (int i = 0 ; i <aa.length ; i++ ) {
      System.out.println("--"+aa[i]);
    }

显然,+ * 不是有效的模式匹配规则表达式,用"//*" "//+"转义后即可得到正确的结果。

"|" 分隔串时虽然能够执行,但是却不是预期的目的,"//|"转义后即可得到正确的结果。

还有如果想在串中使用"/"字符,则也需要转义.首先要表达"aaaa/bbbb"这个串就应该用"aaaa//bbbb",如果要分隔就应该这样才能得到正确结果:

String[] aa = "aaa//bbb//bccc".split("");

由于本人对regular-expression理解程度不深,还望高手指正、补充。

<script type="text/javascript"> <!-- google_ad_client = "pub-4465827781731051"; google_ad_width = 234; google_ad_height = 60; google_ad_format = "234x60_as"; google_ad_type = "text_image"; google_ad_channel =""; //--> </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-4465827781731051&dt=1126781953500&format=234x60_as&output=html&ad_type=text_image&nloc=http://blog.csdn.net/fckeditor/editor/fckeditor.html?InstanceName=Editor_Edit_FCKEditor&Toolbar=Default&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=32&u_tz=480&u_his=5&u_java=true" frameborder="0" width="234" scrolling="no" height="60" allowtransparency="65535">
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值