正则表达式捕获未知数量的重复组 [英] Regex to capture unknown number of repeated groups

查看:174
本文介绍了正则表达式捕获未知数量的重复组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个正则表达式,以便在Java程序中使用,该程序将识别输入中可能出现未知次数的模式。我愚蠢的小例子是:

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 =(?:。*(ht)。*)*;

然后我尝试通过循环matcher.group(i)从小屋很热这样的行中访问匹配。它只记住最后一个匹配(在这种情况下,热),因为只有一个捕获组 - 我猜想matcher.group(1)的内容会被重写,因为捕获组被重用。但是,我想要的是某种包含 hut和hot的数组。

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

有更好的方法吗? FWIW,我真正想要做的是在信号词之后拾取所有(可能是多字的)专有名词,其间可能有其他单词和标点符号。因此,如果看到是信号,我们我看到鲍勃与约翰史密斯和他的妻子玛格丽特,我想要{鲍勃,约翰史密斯,玛格丽特}。

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"}.

推荐答案

(类似问题:具有可变数量的组的正则表达式?

这是不可能的。你最好的选择是使用 ht ,然后使用

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

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

功能 存在于.NET中,但如上所述,Java中没有对应物。

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

这篇关于正则表达式捕获未知数量的重复组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆