gpt4 book ai didi

java - 在Java中使用正则表达式多次匹配一个字符串

转载 作者:行者123 更新时间:2023-12-02 23:17:21 25 4
gpt4 key购买 nike

我在使以下正则表达式工作时遇到一些问题。我想要以下字符串:

"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'

我做错了什么? (P.s.,我在 regexpal.com 上检查了相同的正则表达式并遇到了同样的问题)。看来同一个词不会匹配两次。我该怎么做才能达到我想要的结果?

谢谢。

--------------------------------

编辑:感谢所有的建议!我最终这样做了(因为它增加了能够轻松指定“n-gram”数量的灵 active ):

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

最佳答案

匹配项不能重叠,这解释了您的结果。这是一个潜在的解决方法,利用 capturing groupspositive lookahead :

Pattern word = Pattern.compile("(\\w+)(?=(\\s\\w+))");
Matcher m = word.matcher("Please enter your name here");

while (m.find()) {
System.out.println(m.group(1) + m.group(2));
}
Please enterenter youryour namename here

关于java - 在Java中使用正则表达式多次匹配一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com