Java 正则表达式抛出 java.util.regex.PatternSyntaxException : Illegal/unsupported escape sequence for the letter g

标签 java regex

我需要查看字符串中是否存在整个单词。这是我尝试这样做的方式:

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 正则表达式模式中转义字母字符。

参见 Java regex documentation :

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/

相关文章:

java - ArrayBlockingQueue v/s BlockingBuffer.decorate(new BoundedFifoBuffer()

java - 从文件中读取

javascript - Google Apps 脚本在 Google 表格中进行多个查找和替换正则表达式

python - 在字符串中查找最重复(不是最常见)序列的算法(又名串联重复)

java - 在Java中,如何在两个不同的列中为相同的数据类型设置单元格编辑器?

java - 在 JBOSS 应用程序服务器下运行的 Java 应用程序中的数据库连接池

javascript - $regex 如何在 mongoose 中以空值工作

javascript - 替换两个引号之间的字符串

java - 如何为用 java 编写的文本编辑器实现自动完成?

尝试匹配 URL 的 JavaScript 正则表达式语法错误会导致意外标记 ^