在 Java 中用转义前面的特殊字符替换特殊字符 [英] Replace special character with an escape preceded special character in Java

查看:55
本文介绍了在 Java 中用转义前面的特殊字符替换特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的java代码中,如果一个字符串输入有任何提到的特殊字符,它应该以\

In my java code, if a string input has got any of the special characters mentioned, that should get preceded by \

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

Special character set is {+, -, &&, ||, !, (, ), {, },[, ], ^, "", ~, *, ?, :, }. I tried using String.replaceAll(old,new) but to my surprise its not working, even though I am giving proper values for 'old' and 'new'.

if old=":",new=":"

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

I put the special chars in a String array, iterated it in a for loop, checked whether it is present in the string, if yes, input.replaceAll(":","\:"). But its not giving me the intended output. Please help

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

    for (int i = 0; i < arr.length; i++) {
//'search' is my input string

        if (search.contains((String) arr[i])) {

            String oldString = (String) arr[i];

            String newString = new String("\" + arr[i]);
            search = search.replaceAll(oldString, newString);
            String newSearch = new String(search.replaceAll(arr[i],
                    newString));


        }
    }

推荐答案

一旦您意识到 replaceAll 需要一个正则表达式,只需将您的字符编码为正则表达式即可.

Once you realise replaceAll takes a regex, it's just a matter of coding your chars as a regex.

试试这个:

String newSearch = search.replaceAll("(?=[]\[+&|!(){}^"~*?:\\-])", "\\");

那个奇怪的正则表达式是一个向前看" - 一个非捕获断言,以下字符匹配某些东西 - 在这种情况下是一个字符类.

That whacky regex is a "look ahead" - a non capturing assertion that the following char match something - in this case a character class.

请注意,除了 ] 之外,您不需要对字符类中的字符进行转义(即使是第一个或最后一个减号也不需要转义).

Notice how you don't need to escape chars in a character class, except a ] (even the minus don't need escaping if first or last).

\\ 是您编写正则表达式文字 的方式(Java 转义一次,正则表达式转义一次)

The \\ is how you code a regex literal (escape once for java, once for regex)


这是对这项工作的测试:


Here's a test of this working:

public static void main(String[] args) {
    String search = "code:xy";
    String newSearch = search.replaceAll("(?=[]\[+&|!(){}^"~*?:\\-])", "\\");
    System.out.println(newSearch);
}

输出:

code:xy

这篇关于在 Java 中用转义前面的特殊字符替换特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆