Regex to capture unknown number of repeated groups

旧时模样 提交于 2019-12-01 07:24:50

问题


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.



来源:https://stackoverflow.com/questions/5444816/regex-to-capture-unknown-number-of-repeated-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!