Regex problem: I want to get groups twice, but don't know how to solve it.
Here is code:
public static void multiGroupTest() {
// Pattern p = Pattern.compile("(\\w+)(\\d\\d)(\\w+)");
Pattern p = Pattern.compile("([A-Z]{1})(\\d+)([A-Za-z]+)");
String str = "X89SuperJavaJavaX89SuperJava";
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
}
OK, the result is:
X
89
SuperJavaJavaX
What i want to get is:
X
89
SuperJavaJava
X
89
SuperJava
How can I separate the two matches?
Change your Pattern to add a negative lookahead for the digit:
Pattern p = Pattern.compile("([A-Z]{1})(\\d+)([A-Za-z]+)(?!\\d)");
String str = "X89SuperJavaJavaX89SuperJava";
Output
X
89
SuperJavaJava
X
89
SuperJava
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