Does anyone know which group in regular expression really does comparable work

Say I have a regex like fowllowing: {"(group 1) | (group 2) (group 3) | .... (group n)"} to match the input String object, if it is successful, how can I find out which group of the above n-groups corresponds to this String object? I am using regex lib in java.util. Thanks guys.

+3
source share
2 answers

Here is the way:

import java.util.regex.*;

public class Test {
    public static void main(String[] args) {
        String text = "12 ab ^&";
        String regex = "(\\d+)|([a-z]+)|(\\p{Punct}+)";
        Matcher m = Pattern.compile(regex).matcher(text);
        while(m.find()) {
            System.out.println("\nmatched text: "+m.group());
            for(int i = 1; i <= m.groupCount(); i++) {
                System.out.println("   group "+i+"? "+(m.group(i) != null));
            }
        }
    }
}

output:

matched text: 12
   group 1? true
   group 2? false
   group 3? false

matched text: ab
   group 1? false
   group 2? true
   group 3? false

matched text: ^&
   group 1? false
   group 2? false
   group 3? true
+3
source

You can use the methods in the Matcher object to see which groups match. Here is an example:

import java.util.regex.*;

class RegexExample
{
    public static void main(String[] args) {
        String input = "foo baz bar foo";

        String regex = "(foo)|(bar)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); ++i) {
                if (matcher.group(i) != null)
                {
                    System.out.println("Group " + i + " matched.");
                }
            }
        } 
    }
}

Output:

Group 1 matched.
Group 2 matched.
Group 1 matched.
+2
source

Source: https://habr.com/ru/post/1731379/


All Articles