我遇到了一些问题,无法让以下正则表达式起作用。我想要匹配以下字符串:
"Please enter your name here"
导致一个包含以下元素的数组:
'please enter', 'enter your', 'your name', 'name here'
目前,我正在使用以下模式,然后创建一个匹配器,并以以下方式进行迭代:
Pattern word = Pattern.compile("[\w]+ [\w]+");
Matcher m = word.matcher("Please enter your name here");
while (m.find()) {
wordList.add(m.group());
}
但是我得到的结果是:
'please enter', 'your name'
我做错了什么?(附注:我在regexpal.com上检查了同样的正则表达式,问题依然存在)。似乎同一个单词不会匹配两次。我该怎么做才能获得想要的结果?
谢谢。
---------------------------------
编辑: 感谢所有建议! 最终我做了这个(因为它增加了灵活性,可以轻松指定“n-gram”的数量):
Integer nGrams = 2;
String patternTpl = "\\b[\\w']+\\b";
String concatString = "what is your age? please enter your name."
for (int i = 0; i < nGrams; i++) {
// Create pattern.
String pattern = patternTpl;
for (int j = 0; j < i; j++) {
pattern = pattern + " " + patternTpl;
}
pattern = "(?=(" + pattern + "))";
Pattern word = Pattern.compile(pattern);
Matcher m = word.matcher(concatString);
// Iterate over all words and populate wordList
while (m.find()) {
wordList.add(m.group(1));
}
}
这会导致:
Pattern:
(?=(\b[\w']+\b)) // In the first iteration
(?=(\b[\w']+\b \b[\w']+\b)) // In the second iteration
Array:
[what, is, your, age, please, enter, your, name, what is, is your, your age, please enter, enter your, your name]
注意:本文的模式来自以下最佳答案:Java regex skipping matches。