Java 正则表达式:仅包含非重复单词的匹配字符串
我遇到这种情况(Java代码): 1) 一个字符串,如:“一次野生探险”应该匹配。 2) 相邻重复单词的字符串:“野生探险”不应匹配 使用此正则表达式:.*\b(\w+)\b\s*\1\b.*我可以匹配包含相邻重复单词的字符串Java 正则表达式:仅包含非重复单词的匹配字符串,java,regex,Java,Regex,我遇到这种情况(Java代码): 1) 一个字符串,如:“一次野生探险”应该匹配。 2) 相邻重复单词的字符串:“野生探险”不应匹配 使用此正则表达式:.*\b(\w+)\b\s*\1\b.*我可以匹配包含相邻重复单词的字符串 如何扭转这种情况,即如何匹配不包含相邻重复字的字符串使用负先行断言,(?!pattern) 解释由以下人员提供: 另见 相关问题 使用负前瞻确保字符串中的字符不会出现多次 使用断言的许多示例 使用lookarounds的非常有启发性的示例 注
如何扭转这种情况,即如何匹配不包含相邻重复字的字符串使用负先行断言,
(?!pattern)
解释由以下人员提供:
另见
-
- 使用负前瞻确保字符串中的字符不会出现多次
-
- 使用断言的许多示例
-
- 使用lookarounds的非常有启发性的示例
注 消极断言只有在您希望积极匹配其他模式时才有意义(参见上面的示例)。否则,您可以只使用布尔补运算符
以否定将
与您以前使用的任何模式匹配
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.*"));
}
哇,谢谢!你在几分钟内回答了我的问题。荣誉我尝试对\b(\w+)\b\s*\1\b和\1\进行负前瞻,这就是为什么没有得到所需的结果。再次感谢。@nash:不客气。另外,我刚刚意识到我不小心把它改成了
\s
,而不是\b\s*
;您只需要使用\s+
。
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))
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.*"));
}