Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx matching between characters

Tags:

java

regex

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!

like image 520
hielsnoppe Avatar asked Sep 13 '12 08:09

hielsnoppe


People also ask

How do I match a character in regex?

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).

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does ?= Mean in regular expression?

?= 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).


1 Answers

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));
like image 96
Keppil Avatar answered Oct 04 '22 19:10

Keppil