使用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

相關文章
相關標籤/搜索