Wednesday, August 15, 2012

JDK String.split is using regEx

JDK String.split method is using regEx.

For example, a String “1|abc|999”, we want to split it by “|” and get an array [“1”, “abc”, “999”]

Using this code does not work as we expected.

“1|abc|999”.split(“|”)


This will genereate the result like this [“”, “1”, “|”, “a”, “b”……]



To get the result we want, the easiest way is to use lang-common StringUtils.split(str, delimeter)



If you do want to use jdk string split function, use this code



“1|abc|999”.split(Pattern.quote(“|”))

No comments:

Post a Comment