【问题标题】:replaceAll not working as expected when escaping special characters [duplicate]转义特殊字符时,replaceAll 无法按预期工作[重复]
【发布时间】:2018-08-31 03:27:44
【问题描述】:
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String searchKeyword="Legal'%_";
        String specialChars[]={"_","%","'"};
        for(int i=0;i<specialChars.length;i++)
           searchKeyword=searchKeyword.replaceAll(specialChars[i],"\\"+specialChars[i]);
        System.out.println(searchKeyword);

    }
}

这个 sn-p 试图转义一些特殊字符,但问题是 searchKeyword 没有得到新的替换字符串。

它的输出应该是 Legal\'\%_,但我得到的只是原始字符串作为输出。

请帮帮我。

【问题讨论】:

    标签: java


    【解决方案1】:

    replaceAll(String regex, String replacement) 使用正则表达式:

    替换此字符串中与给定正则匹配的每个子字符串 具有给定替换的表达式。

    您需要将输入字符串中的子字符串替换为特定字符串:replace(CharSequence target, CharSequence replacement)

    替换此字符串中与文字目标匹配的每个子字符串 具有指定文字替换序列的序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 2012-11-20
      • 2011-09-02
      相关资源
      最近更新 更多