[英]How can I find overlapping sets of words with regex expression?
现在,我有一个正则表达式,它看起来像"\\\\w+ \\\\w+"
,可以找到2个单词的短语,但是它们并不重叠。 例如,如果我的句子是The dog ran inside
,则当我需要显示"The dog", "dog ran", "ran inside"
时,输出将显示"The dog", "ran inside"
"The dog", "dog ran", "ran inside"
。 我知道有一种方法可以做到这一点,但是对于使用正则表达式来了解如何做到这一点我还太陌生。
谢谢!
您可以使用前瞻,捕获组和单词边界锚来实现:
Pattern regex = Pattern.compile("\\b(?=(\\w+ \\w+))");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
}
仅使用正则表达式是不可能的,您不能两次匹配相同的字符(“ dog”不能在两个单独的组中)。 这样的事情根本不需要正则表达式,您可以简单地用空格将字符串分割,然后将其组合起来,但是您可以:
>>> words = "The dog ran inside".split(" ")
>>> [" ".join(words[i:i+2]) for i in range(len(words)-1)]
['The dog', 'dog ran', 'ran inside']
如果那不能解决您的问题,请提供更多有关您要完成的工作的详细信息。
使用前瞻性获取第二个单词,将非前瞻性与前瞻性部分串联起来。
# This is Perl. The important bits:
#
# $1 is what the first parens captured.
# $2 is what the second parens captured.
# . is the concatenation operator (like Java's "+").
while (/(\w+)(?=(\s+\w+))/g) {
my $phrase = $1 . $2;
...
}
抱歉,对Java的了解不够,但这在Java中也应该足够容易。
最简单的方法(对于大String来说更快)是使用split :
final String[] arrStr = "The dog ran inside".split(" ");
for (int i = 0, n = arrStr.length - 1; i < n; i++) {
System.out.format("%s %s%n", arrStr[i], arrStr[i + 1]);
}
淘汰
The dog
dog ran
ran inside
找不到正则表达式的把戏
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.