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.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern.
split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.
Introduction to the Python regex split() function The built-in re module provides you with the split() function that splits a string by the matches of a regular expression. In this syntax: pattern is a regular expression whose matches will be used as separators for splitting. string is an input string to split.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
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.
You can use
StringUtils.split("?r")
from commons-lang.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With