By using the appropriate method, this can be done as shown below:
String#split().
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
After this step, if you wish to split lets say a period/dot . which means "any character" in regex, uses either the backslash \ to escape the individual special character like a split("\\."), or it would be using the character class [] to represent literal character(s) like so split("[.]") to escape the entire string like so:- split(Pattern.quote(".")).
String[] parts = string.split(Pattern.quote(".")); // Split on period.
To test it prior, if the string contains certain character(s), just use String#contains().
if (string.contains("-")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain -");
}
Please remember that this will not take an expression that is regular and for that reason, we need to use String#matches() instead. You will have to make use of the positive look around in case you wish to get the split character back in resulting parts. To ensure that the left side is where you want your split character to end up, then commence by using a positive lookbehind prefixing ?<= group on the pattern.
String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556
In case you want to have the split character to end up on the right hand side, then use positive lookahead by prefixing ?= group on the pattern.
String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556
If you would want to limit the number of the resulting parts, then you could supply the given desired number as the 2nd argument of the split() method.
String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
Hope this helps!
Enroll for online Java course and become the expert.
Thanks!