Java 指数14附近的未关闭组

Java 指数14附近的未关闭组,java,regex,Java,Regex,我在这一行中遇到错误: Pattern pattern = Pattern.compile(word + "\\(.*\\)"); 它说: Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed group near index 14 我知道这个错误是当你离开没有逃逸的特殊字符,但我没有看到任何有 完整代码: StyleConstants.s

我在这一行中遇到错误:

Pattern pattern = Pattern.compile(word + "\\(.*\\)");
它说:

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed group near index 14
我知道这个错误是当你离开没有逃逸的特殊字符,但我没有看到任何有

完整代码:

                StyleConstants.setItalic(set, true);
                    for (String word : code.split("\\s")) {
                        Pattern pattern = Pattern.compile(word + "\\(.*\\)");
                        Matcher matcher = pattern.matcher(word);
                        while (matcher.find()) {
                            doc.setCharacterAttributes(matcher.start(), word.length(), set, true);
                        }
                    }
代码是一个字符串。它分解代码并检查每个单词。如果单词匹配,则为其添加颜色

我尝试了以下方法:

Pattern pattern = Pattern.compile("abcd" + "\\(.*\\)");
log.debug("RegEx: " + pattern);
这很好:

RegEx: abcd\(.*\)
我只能假设您在
word
中有一些未替换的字符

如果在编译时不知道
word
的值,则在调用
compile()
方法之前构建模式并记录它:

String regex = word + "\\(.*\\)";
System.out.println("Regex: \"" + regex + "\"");
Pattern pattern = Pattern.compile(regex);

word
的值是多少?如果它有一个regexp字符,也必须转义。那么现在您在哪里告诉我们
word
的内容?我如何知道word的内容?Word是字符串代码的一部分。若字符串是“somelargstring”,那个么循环将遍历“Some”、“large”和“string”并检查每个字符串。若代码是“some function()”,那个么它应该经过“some”和“function()”,但我怎么知道word是否包含一些不合适的字符呢?我应该在编译之前检查每个单词吗?没有其他选择?是的,你必须在编译之前扫描每个单词
compile()
不知道什么是单词,什么是单词——它将整个事情看作一个正则表达式模式,必须使用正则表达式语法。