Since String.split()
works with regular expressions, this snippet:
String s = \"str?str?argh\";
s.split(\"r?\");
... yields: <
Escape the ?
:
s.split("r\\?");
You can use
StringUtils.split("?r")
from commons-lang.
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]
A general solution using just Java SE APIs is:
String separator = ...
s.split(Pattern.quote(separator));
The quote
method returns a regex that will match the argument string as a literal.
Use Guava Splitter:
Extracts non-overlapping substrings from an input string, typically by recognizing appearances of a separator sequence. This separator can be specified as a single character, fixed string, regular expression or CharMatcher instance. Or, instead of using a separator at all, a splitter can extract adjacent substrings of a given fixed length.
try
String s = "str?str?argh";
s.split("r\?");