【问题标题】:Java - How to add "\\" infront of "(" or ")" in a StringJava - 如何在字符串中的“(”或“)”前面添加“\\”
【发布时间】:2019-12-09 19:06:33
【问题描述】:

我正在阅读一份文档并删除其中的一些字词。 我有以下功能:

 //Takes a string and removes the word
 private static String removeWord(String string, String word) {
    if (string.contains(word)) {
        String tempWord = word.trim();
        string = string.replaceAll(tempWord, "");
    }
    return string;
}

例如,当我尝试替换时遇到以下问题:

Hello world (

给我以下错误:

原因:java.util.regex.PatternSyntaxException:索引 14 附近的未封闭组

做一些研究我发现这是因为split() 需要一个正则表达式,而括号用于标记正则表达式中的捕获组。

所以我这样做了:

private static String removeWord(String string, String word) {
    if (string.contains(word)) {
        String [] temp = word.split(" ");
        word = "";
        for (int i = 0; i < temp.length ; i++) {
            if (temp[i].equals("(")){
                word += " "+ "\\(";
            }else if (temp[i].equals(")")){
                word += " "+ "\\)";
            } else {
                word += temp[i] + " ";
            }
        }
        String tempWord = word.trim();
        string = string.replaceAll(tempWord, "");
    }
    return string;
}

此代码不是最佳解决方案。因为有时字符串就像(Hello world

如何改进这部分代码?

【问题讨论】:

  • 只需在将字符串提供给.split 方法之前使用Pattern.quote

标签: java string replace split


【解决方案1】:

您似乎正在尝试手动转义正则表达式。我的建议是:不要。

即使您成功处理了(),您仍然有大量其他在正则表达式中具有特殊含义的字符需要转义,例如*+[]\? 仅举几例。

幸运的是,有一个名为Pattern.quote 的非常方便的方法可以自动为您执行此操作:

 private static String removeWord(String string, String word) {
    if (string.contains(word)) {
        String tempWord = word.trim();
        string = string.replaceAll(Pattern.quote(tempWord), "");
    }
    return string;
}

【讨论】:

    【解决方案2】:
    private static String removeWord(String string, String word) {
        return string.replaceFirst("\\W+" + word + "\\W+","");
    }
    

    \W 匹配非单词字符enter link description here .如果要替换所有匹配项,也可以使用 replaceAll,如果要替换特定数量的匹配项,则可以在循环中使用 replaceFirst。

    【讨论】:

    • 不工作Caused by: java.util.regex.PatternSyntaxException: Unclosed group near index 14 DEBUGG = \W+Hello wold (\W+
    • 是的,您需要先转义才能处理 word 中的所有特殊字符。这个想法是展示如何使用 \W 而不是手动拆分和查找每个字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多