我需要查看字符串中是否存在整个单词。这是我尝试这样做的方式:
if(text.matches(".*\\" + word + "\\b.*"))
// do something
大多数单词都在运行,但是以 g
开头的单词会导致错误:
Exception in thread "main" java.util.regex.PatternSyntaxException:
Illegal/unsupported escape sequence near index 3
.*\great life\b.*
^
我该如何解决这个问题?
最佳答案
错误的实际原因是您无法在未构成有效转义构造的 Java 正则表达式模式中转义字母字符。
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
我会用
Matcher m = Pattern.compile("\\b" + word + "\\b").matcher(text);
if (m.find()) {
// A match is found
}
如果一个单词可能包含/以特殊字符开始/结束,我会使用
Matcher m = Pattern.compile("(?!\\B\\w)" + Pattern.quote(word) + "(?<!\\w\\B)").matcher(text);
if (m.find()) {
// A match is found
}
关于Java 正则表达式抛出 java.util.regex.PatternSyntaxException : Illegal/unsupported escape sequence for the letter g,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43616202/