How to know which part of regex matched?

Viewed 80

regex= (i.*d.*n.*t.*)|(p.*r.*o.*f.*)|(u.*s.*r.*) string to be matched= profile

Now the regex will match with the string. But I want to know which part matched.

Meaning, I want (p.*r.*o.f.) as the output

How can I get do this in Java?

2 Answers

You can check if which group matched:

Pattern p = Pattern.compile("(i.*d.*n.*t.*)|(p.*r.*o.*f.*)|(u.*s.*r.*)");
Matcher m = p.matcher("profile");
m.find();
for (int i = 1; i <= m.groupCount(); i++) {
    System.out.println(i + ": " + m.group(i));
}

Will output:

1: null
2: profile
3: null

Because the second line is not null, it's (p.*r.*o.*f.*) that matched the string.

In your case, It seems like you can distinguish those subpatterns with the first letter. If the first letter of the match is 'p', then it will be your desired pattern. Maybe you can construct simple function to distinguish these.

Related