2

在我的 java 代码中,我想要一些类似的东西,如果一个字符串输入有任何提到的特殊字符,那应该在前面加上\.

特殊字符集是{+, -, &&, ||, !, (, ), {, },[, ], ^, "", ~, *, ?, :, \}. 我尝试使用inputString.replaceAll(old,new)但令我惊讶的是它不起作用,即使我为“旧”和“新”提供了正确的值。

我将特殊字符放在一个字符串数组中,在 for 循环中对其进行迭代,检查它是否存在于字符串中,如果是,input.replaceAll(":","\\:"). 但它没有给我预期的输出。请帮忙。

 String[] arr = { "+", "-", "&&", "||", "!", "(", ")", "{", "}",
                    "[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" };

        for (int i = 0; i < arr.length; i++) {
            System.out.println("arr[" + i + "]>>>>>>>>>>>>>>>" + arr[i]);
            System.out.println(search.contains((String) arr[i])
                    + "---------->" + arr[i]);

            if (search.contains((String) arr[i])) {
                System.out.println("..index..."+search.indexOf((String) arr[i]));
                String oldString = (String) arr[i];
                System.out.println("check if it has old string"
                        + search.contains(oldString));
                String newString = new String("\\" + arr[i]);
                System.out
                        .println("About to replace special chars....with..."
                                + newString);

                search = search.replaceAll(oldString, newString);
                String newSearch = new String(search.replaceAll(arr[i],
                        newString));
                System.out
                        .println("Search String after replaceAll is ------------->: "
                                + newSearch);
                System.out.println("--------------"
                        + search.replaceAll(arr[i], newString)
                        + "---------------" + search);

            }
        }
4

2 回答 2

0

不确定你是否有答案。今天我也在尝试。我修改了您的代码以使用我的解决方案。希望它对你有帮助。

String search = "$&+";

String[] arr = { "+", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" };

for (int i = 0; i < arr.length; i++) {
 System.out.println("arr[" + i + "]>>>>>>>>>>>>>>>" + arr[i]);
 System.out.println(search.contains((String) arr[i])
         + "---------->" + arr[i]);

 if (search.contains((String) arr[i])) {
     System.out.println("..index..."+search.indexOf((String) arr[i]));
     String oldString = (String) arr[i];
     System.out.println("check if it has old string"
             + search.contains(oldString));
     String newString = new String("\\\\" + arr[i]);
     System.out
             .println("About to replace special chars....with..."
                     + newString);

     search = search.replace("\\" + oldString, newString);
     String newSearch = new String(search);
     System.out
             .println("Search String after replaceAll is ------------->: "
                     + newSearch);

 }

}

于 2013-08-22T11:18:20.627 回答
0

您需要先转义单个反斜杠(在转义其他任何内容之前),或者您双重转义一些反斜杠。

例子:1+1

替换+\+=>1\+1

替换\\\=> 1\\+1(哎呀!)

于 2013-01-07T13:53:21.520 回答