Question

I have source string "This is my test string" and would like to extract a value of it using a specific pattern: "{0} is my {1} string"

I'd like to extract eg This and test here. How do I write that with regex matching group?

The following is some kind of pseudocode I came up with. But I don't know exactly how to implement these matching groups:

Matcher match = Pattern.compile("(.*) is my (.*) string").matcher("This is my test string");
if (match.matches()) {
    for (int i = 0; i <= match.groupCount(); i++) {
        Sysout(match.group(i));
    }
}

prints:

This is my test string
This
test

But I'd like to get:

This
test

How can I prevent to take the whole string as a matching group? Or could I as well directly bind a match to a specific matching group? Like {1} is my {0} string where test would go to match.group(0)? Is that possible?

Était-ce utile?

La solution

Apart from the group index problem mentioned in the comment, there is another question:

[...] could I as well directly bind a match to a specific matching group? Like {1} is my {0} string where test would go to match.group(0)? Is that possible?

Not with Java 6. With Java 7+, you can use named capturing groups:

Pattern.compile("(?<first>.*) is my (?<second>.*) string")

You can then use .group("first") and .group("second") on your Matcher instance.

Note that .group() is equivalent to .group(0).

Autres conseils

group 0 is ALWAYS the whole matched string. matching groups that you define within a regexp always start from 1.

have a loot at the javadoc for Matcher.group(int):

Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group()

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top