gpt4 book ai didi

java - 正则表达式 :match string containing only non repeating words

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:57:35 25 4
gpt4 key购买 nike

我有这种情况(Java代码):1) 一个字符串,如:“A wild adventure”应该匹配。2) 带有相邻重复词的字符串:“A wild wild adventure”不应该匹配。

使用这个正则表达式:.*\b(\w+)\b\s*\1\b.* i 可以匹配包含相邻重复单词的字符串。

如何扭转这种情况,即如何匹配不包含相邻重复词的字符串

最佳答案

使用否定先行断言,(?!pattern)

    String[] tests = {
"A wild adventure", // true
"A wild wild adventure" // false
};
for (String test : tests) {
System.out.println(test.matches("(?!.*\\b(\\w+)\\s\\1\\b).*"));
}

解释由 Rick Measham's explain.pl 提供:

REGEX: (?!.*\b(\w+)\s\1\b).*
NODE EXPLANATION
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1
or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
\1 what was matched by capture \1
--------------------------------------------------------------------------------
\b the boundary between a word char (\w)
and something that is not a word char
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
.* any character except \n (0 or more times
(matching the most amount possible))

另见

相关问题


注意事项

否定断言只有在还有其他您想要肯定匹配的模式时才有意义(参见上面的示例)。否则,您可以只使用 boolean 补码运算符 ! 来否定与您之前使用的任何模式的匹配

String[] tests = {
"A wild adventure", // true
"A wild wild adventure" // false
};
for (String test : tests) {
System.out.println(!test.matches(".*\\b(\\w+)\\s\\1\\b.*"));
}

关于java - 正则表达式 :match string containing only non repeating words,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2879316/

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