正则表达式捕获未知数量的重复组

编程入门 行业动态 更新时间:2024-10-21 03:36:48
本文介绍了正则表达式捕获未知数量的重复组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个正则表达式,以便在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.

更多推荐

正则表达式捕获未知数量的重复组

本文发布于:2023-11-01 18:04:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数量   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!