开发者

Regex to capture unknown number of repeated groups

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 ov开发者_如何学Pythonerwritten 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"}.


(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜