我正在尝试将 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 Pattern
和 Matcher
实现吗?如果是,我的错误是什么?
最佳答案
如果你想确保有连续的结果,你可以使用 \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/