我有一些文字;我想提取没有用标点符号分隔的单词对。这是代码:
//n-grams
Pattern p = Pattern.compile("[a-z]+");
if (n == 2) {
p = Pattern.compile("[a-z]+ [a-z]+");
}
if (n == 3) {
p = Pattern.compile("[a-z]+ [a-z]+ [a-z]+");
}
Matcher m = p.matcher(text.toLowerCase());
ArrayList<String> result = new ArrayList<String>();
while (m.find()) {
String temporary = m.group();
System.out.println(temporary);
result.add(temporary);
}
问题是它会跳过一些匹配项。例如
"My name is James"
,对于 n = 3,必须匹配
"my name is" and "name is james"
,但它只匹配第一个。有办法解决这个问题吗?
最佳答案
您可以使用 lookahead 中的组来捕获它
(?=(\b[a-z]+\b \b[a-z]+\b \b[a-z]+\b))
这导致它分成两组..所以在你的情况下它会是
Group1->我的名字是
Group2->名字是 james
关于Java 正则表达式跳过匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13330401/