user697911 user697911 - 1 month ago 8
Java Question

Regular expression not capturing expected groups

I suppose group[1] should be "xyz" and group[2] should be 'ab' for this input string.

String p = "(.+)\\s(ab|cd|efg)";

Pattern pattern = Pattern.compile(p);

String str = "xyz ab";

Matcher m = pattern.matcher(str);

System.out.println(m.group(1));
System.out.println(m.group(2));

Answer

You have to call m.find()

String p = "(.+)\\s(ab|cd|efg)";

    Pattern pattern = Pattern.compile(p,Pattern.DOTALL);

    String str = "xyz ab";

    Matcher m = pattern.matcher(str);

    if (m.find()) { 
        System.out.println(m.group(1));
        System.out.println(m.group(2));
    }

find() will Attempts to find the next subsequence of the input sequence that matches the pattern.

Output :

xyz
ab

you can also call m.matches(); before fetching group, instead of if (m.find()) but it's a good practice to use find() or matches() with if to verify the match found

Comments