I want to split a string using a delimiter, for example split "004-034556"
into two separate strings by the delimiter "-"
:
part1 = "004";
part2 = "034556";
That means the first string will contain the characters before '-'
, and the second string will contain the characters after '-'
.
I also want to check if the string has the delimiter ('-'
) in it.
Best Answer
Use the appropriately named method
String#split()
.Note that
split
's argument is assumed to be a regular expression, so remember to escape special characters if necessary.For instance, to split on a period/dot
.
(which means "any character" in regex), use either backslash\
to escape the individual special character like sosplit("\\.")
, or use character class[]
to represent literal character(s) like sosplit("[.]")
, or usePattern#quote()
to escape the entire string like sosplit(Pattern.quote("."))
.To test beforehand if the string contains certain character(s), just use
String#contains()
.Note, this does not take a regular expression. For that, use
String#matches()
instead.If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing
?<=
group on the pattern.In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing
?=
group on the pattern.If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of
split()
method.