java - 匹配正则表达式组以在 java 中列出(赫斯特模式)

标签 java regex regex-group

我正在尝试将 Hearst-Patterns 与 Java 正则表达式匹配,这是我的正则表达式:

<np>(\w+)<\/np> such as (?:(?:, | or | and )?<np>(\w+)<\/np>)*

如果我有一个带注释的句子:

I have a <np>car</np> such as <np>BMW</np>, <np>Audi</np> or <np>Mercedes</np> and this can drive fast.

我想得到组:

1. car
2. [BMW, Audi, Mercedes]

更新:这是我当前的 java 代码:

Pattern pattern = Pattern.compile("<np>(\\w+)<\\/np> such as (?:(?:, | or | and )?<np>(\\w+)<\\/np>)*");
Matcher matcher = pattern.matcher("I have a <np>car</np> such as <np>BMW</np>, <np>Audi</np> or <np>Mercedes</np> and this can drive fast.");

while (matcher.find()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

但是第二组元素只包含 Mercedes,我怎样才能得到第二组的所有匹配项(maby 作为数组)?这可以用 java PatternMatcher 实现吗?如果是,我的错误是什么?

最佳答案

如果你想确保有连续的结果,你可以使用 \G强制匹配项与先前匹配项连续的 anchor :

Pattern p = Pattern.compile("<np>(\\w+)</np> such as|\\G(?:,| or| and)? <np>(\\w+)</np>");

注意:\G anchor 表示先例匹配的结尾或字符串的开头。为避免匹配字符串的开头,您可以添加 lookbehind (?<!^)\G之后

关于java - 匹配正则表达式组以在 java 中列出(赫斯特模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20340198/

相关文章:

html - 正则表达式 - 在 Dreamweaver 中查找和替换

java - 将具有 transient 属性的对象写入流 (Java)

java - 使用 Java、Eclipse 创建 RESTful Web 服务的教程。 Apache Tomcat,不工作

javascript - 字符串的正则表达式 - 长度为 9,第三个字符字母和剩余数字

javascript - 用于替换中间字母的正则表达式

Javascript 正则表达式与非捕获组作为两种选择

Python:非捕获组在正则表达式中不起作用

javascript - java中的文本编辑器

java - 在 Android java 中实现按钮有哪些不同的方法?

正则表达式:匹配可能包含字符 '-' 的字母数字字符串