1. 背景
String的split方法在項目中使用很廣泛,但是這里面其實有些坑衙荐,截取的字段數(shù)目可能不是想要的荆陆,本文闡述這些內(nèi)容,增加記性腐芍。
2. split方法介紹
首先可以看下javadoc中關(guān)于split的介紹差导。
String [] split(String regex)
Splits this string around matches of the given [regular expression](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum).
String[] split(String regex, int limit)
Splits this string around matches of the given [regular expression](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#sum).
簡而言之,split方法就是根據(jù)輸入的正則表達式分割字符串猪勇。
那么這又有什么毛病咧设褐,別急。
3. split的limit參數(shù)
在項目中泣刹,經(jīng)常被使用的就是第一個方法助析,輸入一個參數(shù)regex(其實limit為0),仔細看下官方的描述
This method works as if by invoking the two-argument [`split`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
該方法會導致后面的空串被去掉,比如
“beijing:and:shenzhen:”, 用:分割后椅您,得到的結(jié)果為{ "beijing", "and", "shenzhen" }外冀,而有時項目是希望得到4個字段的,會造成線上嚴重問題掀泳。
4. split的regex參數(shù)
該參數(shù)是個正則表達式雪隧,那么要記住,在傳入正則表達式的特殊字符時员舵,可能會出呼意料的結(jié)果脑沿,要加上轉(zhuǎn)義字符。比如
“beijing|and|shenzhen”, 用"http://|"分割后马僻,得到的結(jié)果為{ "beijing", "and", "shenzhen" }庄拇,而有時項目是希望得到4個字段的,會造成線上嚴重問題巫玻。
具體有哪些特殊字符丛忆,看下split的源碼介紹祠汇。
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
...
}
if條件判斷里面是重點,主要分為兩個部分:
- 單字符的字符串并且該字符不是為正則中的特殊字符熄诡,比如.$|()[{^?*+\
(regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1)
- 兩個字符的字符串可很,第一個字符為轉(zhuǎn)義字符(\),第二個字符非數(shù)字或這字母凰浮,其實就是將特殊字符作為分割符號我抠。
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE)
在這里需要指出的是,此處判斷為非數(shù)字或字母采用了或(|)的位運算袜茧,很巧妙菜拓。