Q:

How to find the part of the regexp pattern that matched the input in java?

I have pattern "abc|de.|ghi" and an input of "def". How do I find the part of the pattern that matched "def"? So, in this example the result I want is "de.". Not "def", which is all I have been able to get using group and start/end methods.
In code:
Pattern p = Pattern.compile("abc|de.|ghi");
Matcher m = p.matcher("def");
if(matcher.find()) {
    // Here I want to get the String "de." somehow
}

A:

It's kind of round about, but you can do what you want with capture groups:
Pattern p = Pattern.compile("(abc)|(de.)|(ghi)");
Matcher m = p.matcher("def");
if(m.find()) {
    if (m.group(1) != null)
        System.out.println("Matched \"abc\"");
    if (m.group(2) != null)
        System.out.println("Matched \"de.\"");
    if (m.group(3) != null)
        System.out.println("Matched \"ghi\"");
}

