I have this string (Java 1.5):
:alpha;beta:gamma;delta
I need to get an array:
{":alpha", ";beta", ":gamma", ";delta"}
What is the most convenient way to do it in Java?
Summary: To split a string and keep the delimiters/separators you can use one of the following methods: Use a regex module and the split() method along with \W special character. Use a regex module and the split() method along with a negative character set [^a-zA-Z0-9] .
String myString = "Jane-Doe"; String[] splitString = myString. split("-"); We can simply use a character/substring instead of an actual regular expression. Of course, there are certain special characters in regex which we need to keep in mind, and escape them in case we want their literal value.
str.split("(?=[:;])")
This will give you the desired array, only with an empty first item. And:
str.split("(?=\\b[:;])")
This will give the array without the empty first item.
(?=X)
which is a zero-width positive lookahead (non-capturing construct) (see regex pattern docs).[:;]
means "either ; or :"\b
is word-boundary - it's there in order not to consider the first :
as delimiter (since it is the beginning of the sequence)To keep the separators, you can use a StringTokenizer:
new StringTokenizer(":alpha;beta:gamma;delta", ":;", true)
That would yield the separators as tokens.
To have them as part of your tokens, you could use String#split
with lookahead.
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