我在使以下正则表达式工作时遇到了一些问题。我想要以下字符串:
"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'
我究竟做错了什么?(Ps,我在 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