zaki41
zaki41

Reputation: 81

How to know which part of regex matched?

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?

Upvotes: 3

Views: 311

Answers (2)

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

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.

Upvotes: 1

MyBug18
MyBug18

Reputation: 2230

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.

Upvotes: 0

Related Questions