Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

separate the two matches

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?

like image 799
Levi Avatar asked Jan 17 '26 02:01

Levi


1 Answers

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
like image 140
Mena Avatar answered Jan 19 '26 14:01

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!