Home » Java » The Java string segmentation "|" and "Bug." (remem...

The Java string segmentation "|" and "Bug." (remember)

1. background:
| "and"
. "
At present, more
developer did not view source habits, so the java.lang.String.split (String) method to understand, just stay in the know is based on the parameters of the original string segmentation, but do not understand the principle of segmentation, it will not lead to realize the Bug.
here



2. instance:

s.replaceAll (".", "will return a String in) which every character has been replaced by a character
'
S.split (".") always, returns, a, zero, length, array, of, String

"Ab|cd.ReplaceAll" ("|", "/" will return "/a/b/|/c/d/"
)
"Ab|cd.Split" ("|") will return array with six (elements:!) [a, B, C, d]

, |.





3. production principle:

public, String[], split (String, regex) {
return, split (regex, 0) ;
}

The above is the split method in the String class source code, the parameter name is regex, you should understand that we see here in the parameters used to partition is actually a regular expression, and Java will use regular to split the original string. "|" and "." is the regular expression in the symbol, they are not in regular the expression of the literal meaning, the nature is not expected after the division of the string array.



4. solutions:

"|" and "." added to the front turn symbol, is to change the "\|" and ".
."

Latest