I'm trying to split a String in Java. The splits should occur in between two characters one of which is an alphabetic one (a-z, A-Z) and the other numeric (0-9). For example:
String s = "abc123def456ghi789jkl";
String[] parts = s.split(regex);
System.out.println(Arrays.deepToString(parts));
Output should be [abc, 123, def, 456, ghi, 789, jkl]
. Can someone help me out with a matching regular expression?
Thanks in advance!
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
You can use a combination of look-ahead and look-behind:
String s = "abc123def456ghi789jkl";
String regex = "(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)";
String[] parts = s.split(regex);
System.out.println(Arrays.deepToString(parts));
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