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

<p>在使用String.split方法分隔字符串时,分隔符若是用到一些特殊字符,可能会得不到咱们预期的结果。 <br />咱们看jdk doc中说明 <br />public String[] split(String regex) <br /> Splits this string around matches of the given regular expression.&#160; <br />参数regex是一个 regular-expression的匹配模式而不是一个简单的String,他对一些特殊的字符可能会出现你预想不到的结果,好比测试下面的代码: <br />用竖线 | 分隔字符串,你将得不到预期的结果 <br />&#160;&#160;&#160; String[] aa = &quot;aaa|bbb|ccc&quot;.split(&quot;|&quot;); <br />&#160;&#160;&#160; //String[] aa = &quot;aaa|bbb|ccc&quot;.split(&quot;\\|&quot;); 这样才能获得正确的结果 <br />&#160;&#160;&#160; for (int i = 0 ; i &lt;aa.length ; i++ ) { <br />&#160;&#160;&#160;&#160;&#160; System.out.println(&quot;--&quot;+aa[i]); <br />&#160;&#160;&#160; } <br />用竖 * 分隔字符串运行将抛出java.util.regex.PatternSyntaxException异常,用加号 + 也是如此。 <br />&#160;&#160;&#160; String[] aa = &quot;aaa*bbb*ccc&quot;.split(&quot;*&quot;); <br />&#160;&#160;&#160; //String[] aa = &quot;aaa|bbb|ccc&quot;.split(&quot;\\*&quot;); 这样才能获得正确的结果&#160;&#160;&#160; <br />&#160;&#160;&#160; for (int i = 0 ; i &lt;aa.length ; i++ ) { <br />&#160;&#160;&#160;&#160;&#160; System.out.println(&quot;--&quot;+aa[i]); <br />&#160;&#160;&#160; } <br />显然,+ * 不是有效的模式匹配规则表达式,用&quot;\\*&quot; &quot;\\+&quot;转义后便可获得正确的结果。 <br />&quot;|&quot; 分隔串时虽然可以执行,可是却不是预期的目的,&quot;\\|&quot;转义后便可获得正确的结果。 <br />还有若是想在串中使用&quot;\&quot;字符,则也须要转义.首先要表达&quot;aaaa\bbbb&quot;这个串就应该用&quot;aaaa\\bbbb&quot;,若是要分隔就应该这样才能获得正确结果: <br />String[] aa = &quot;aaa\\bbb\\bccc&quot;.split(&quot;\\\\&quot;);</p>java

相关文章
相关标签/搜索