Regex to capture unknown number of repeated groups

2019-02-19 03:29发布

问题:

I'm try to write a regular expression to use in a Java program that will recognize a pattern that may appear in the input an unknown number of times. My silly little example is:

String patString = "(?:.*(h.t).*)*";

Then I try to access the matches from a line like "the hut is hot" by looping through matcher.group(i). It only remembers the last match (in this case, "hot") because there is only one capture group--I guess the contents of matcher.group(1) get overwritten as the capture group is reused. What I want, though, is some kind of array containing both "hut" and "hot."

Is there a better way to do this? FWIW, what I'm really trying to do is to pick up all the (possibly multiword) proper nouns after a signal word, where there may be other words and punctuation in between. So if "saw" is the signal and we have "I saw Bob with John Smith, and his wife Margaret," I want {"Bob","John Smith","Margaret"}.

回答1:

(Similar question: Regular expression with variable number of groups?)

This is not possible. Your best alternative is to use h.t, and use a

while (matcher.find()) {
    ...
    ... matcher.group(1); ...
    ...
}

The feature does exist in .NET, but as mentioned above, there's no counterpart in Java.