String.split() *not* on regular expression?

Viewed 25223

Since String.split() works with regular expressions, this snippet:

String s = "str?str?argh";
s.split("r?");

... yields: [, s, t, , ?, s, t, , ?, a, , g, h]

What's the most elegant way to split this String on the r? sequence so that it produces [st, st, argh]?

EDIT: I know that I can escape the problematic ?. The trouble is I don't know the delimiter offhand and I don't feel like working this around by writing an escapeGenericRegex() function.

8 Answers

Using directly the Pattern class, is possible to define the expression as LITERAL, and in that case, the expression will be evaluated as is (not regex expression).

Pattern.compile(<literalExpression>, Pattern.LITERAL).split(<stringToBeSplitted>);

example:

String[] result = Pattern.compile("r?", Pattern.LITERAL).split("str?str?argh");

will result:

[st, st, argh]

org.apache.commons.lang.StringUtils has methods for splitting Strings without expensive regular expressions.

Be sure to read the javadocs closely as the behavior can be subtle. StringUtils.split (as in another answer) does not meet the stated requirements. Use StringUtils.splitByWholeSeparator instead:

String s = "str?str?argh";

StringUtils.split(s, "r?");                   //[st, st, a, gh]
StringUtils.splitByWholeSeparator(s, "r?");   //[st, st, argh]
Related