原创 使用String.split方法时要注意的问题收藏

新一篇: 也玩一下excel文档的VBA编程 | 旧一篇: 日文输入时促音、拨音、拗音的输入方法

在使用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理解程度不深,还望高手指正、补充。

发表于 @ 2005年04月29日 12:07:00|评论(loading...)|编辑

新一篇: 也玩一下excel文档的VBA编程 | 旧一篇: 日文输入时促音、拨音、拗音的输入方法

评论

#sedemon 发表于2005-05-12 20:01:00  IP: 221.237.128.*
做个沙法
#sedemon 发表于2005-05-12 20:02:00  IP: 221.237.128.*
我好像不用转义也可以
#guest007 发表于2005-06-01 15:13:00  IP: 61.186.252.*
此问题已烦扰我多日,近日终于找到此处,得解,不慎感激!

另在JDK API里找到此段说明,大意是为了防止正则表达式里的转义符与java语句里的"\"搞混,特用"\\"作转义符。
Backslashes within string literals in Java source code are interpreted as required by the Java Language Specification as either Unicode escapes or other character escapes. It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

#lee 发表于2005-06-08 13:02:00  IP: 61.186.252.*
谢谢,帮我解决了挠头的问题。split(".")应改城split("\\.")
#eyangm 发表于2005-07-04 11:58:00  IP: 61.186.252.*
我也遇到鸟 谢谢哦~~~~~~
#逍遥枫梓 发表于2006-02-03 21:55:00  IP: 127.0.0.*
谢谢你了,能找到例子真是感谢你了。
#逍遥枫梓 发表于2006-02-03 21:55:00  IP: 127.0.0.*
谢谢你了,能找到例子真是感谢你了。
#编程小虫 发表于2006-02-14 09:22:00  IP: 221.221.148.*
请问在split("@@")是什么意思?
#草根看世界 发表于2006-03-03 16:21:00  IP: 221.217.13.*
谢谢
#zhoyan 发表于2007-09-26 16:01:13  IP: 218.242.135.*
非常感谢!解决我的大问题了。
发表评论  


当前用户设置只有注册用户才能发表评论。如果你没有登录,请点击登录
Csdn Blog version 3.1a
Copyright © zmxj