[英]Java regex skipping matches
我有一些文字; 我想提取不被標點符號分隔的單詞對。 這是代碼:
//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);
}
問題在於它跳過了一些匹配項。 例如
“我的名字是詹姆斯”
,對於n = 3,必須匹配
“我的名字是”和“名字是詹姆斯”
,但只匹配第一個。 有辦法解決嗎?
您可以使用超前組捕獲它
(?=(\b[a-z]+\b \b[a-z]+\b \b[a-z]+\b))
這導致它被捕獲為兩個組。因此,在您的情況下
Group1-> my name is
Group2-> name is james
James
在regex定義的正則表達式模式中,將字符串從左到右應用到字符串中,並且一旦在匹配項中使用了源字符,就無法重用它。
例如,正則表達式“ 121”將匹配“ 31212142121”的次數是“ 121 ___121”的兩倍。
我傾向於使用Matcher
的find()
方法的參數:
Matcher m = p.matcher(text);
int position = 0;
while (m.find(position)) {
String temporary = m.group();
position = m.start();
System.out.println(position + ":" + temporary);
position++;
}
因此,在每次迭代之后,它都會根據最后一個開始索引再次搜索。
希望能有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.