Use the return paths: str.split("(?<=\\d)(?=\\D)")
String[] parts = "123XYZ".split("(?<=\\d)(?=\\D)"); System.out.println(parts[0] + "-" + parts[1]);
\d - character class for digits; \d is its negation. Thus, this zero-correspondence statement coincides with the position in which the preceding character is a digit (?<=\d) and the next character is not a digit (?=\D) .
References
Related Questions
- The separation of Java is the use of my characters.
- Is there a way to split strings with String.split () and enable separators?
Alternative solution using limited separation
The following also works:
String[] parts = "123XYZ".split("(?=\\D)", 2); System.out.println(parts[0] + "-" + parts[1]);
It breaks just before we see a number. This is much closer to your original solution, except that since it does not actually correspond to an asymmetric symbol, it does not βeat it upβ. In addition, it uses the limit of 2 , which you really need.
API Links
String.split(String regex, int limit)- If the limit
n greater than zero, the pattern will be applied no more than n - 1 times, the length of the array will be no more than n , and the last record of the array will contain all the input data for the last Corresponding separator.
polygenelubricants
source share