How to split a string in Java -
i have string, "004-034556"
, want split 2 strings:
string1=004 string2=034556
that means first string contain characters before '-'
, , second string contain characters after '-'
. want check if string has '-'
in it. if not, throw exception. how can this?
just use appropriate method: string#split()
.
string string = "004-034556"; string[] parts = string.split("-"); string part1 = parts[0]; // 004 string part2 = parts[1]; // 034556
note takes regular expression, remember escape special characters if necessary.
there 12 characters special meanings: backslash
\
, caret^
, dollar sign$
, period or dot.
, vertical bar or pipe symbol|
, question mark?
, asterisk or star*
, plus sign+
, opening parenthesis(
, closing parenthesis)
, , opening square bracket[
, opening curly brace{
, these special characters called "metacharacters".
so, if want split on e.g. period/dot .
means "any character" in regex, use either backslash \
escape individual special character split("\\.")
, or use character class []
represent literal character(s) split("[.]")
, or use pattern#quote()
escape entire string split(pattern.quote("."))
.
string[] parts = string.split(pattern.quote(".")); // split on period.
to test beforehand if string contains character(s), use string#contains()
.
if (string.contains("-")) { // split it. } else { throw new illegalargumentexception("string " + string + " not contain -"); }
note, not take regular expression. that, use string#matches()
instead.
if you'd retain split character in resulting parts, make use of positive lookaround. in case want have split character end in left hand side, use positive lookbehind prefixing ?<=
group on pattern.
string string = "004-034556"; string[] parts = string.split("(?<=-)"); string part1 = parts[0]; // 004- string part2 = parts[1]; // 034556
in case want have split character end in right hand side, use positive lookahead prefixing ?=
group on pattern.
string string = "004-034556"; string[] parts = string.split("(?=-)"); string part1 = parts[0]; // 004 string part2 = parts[1]; // -034556
if you'd limit number of resulting parts, can supply desired number 2nd argument of split()
method.
string string = "004-034556-42"; string[] parts = string.split("-", 2); string part1 = parts[0]; // 004 string part2 = parts[1]; // 034556-42
Comments
Post a Comment