简体   繁体   English

如何更换所有星号?

[英]How do I replace all asterisks?

In Java, I want to replace all * characters with \\* . 在Java中,我想用\\*替换所有*字符。

Example: Text: select * from blah 示例:文本: select * from blah

Result: select \\\\* from blah 结果: select \\\\* from blah

public static void main(String[] args) {
    String test = "select * from blah";
    test = test.replaceAll("*", "\\*");
    System.out.println(test);
}

This does not work, nor does adding a escape backslash. 这不起作用,也没有添加转义反斜杠。

I figured it out 我想到了

    String test = "select * from blah *asdf";
    test = test.replaceAll("\\*", "\\\\*");
    System.out.println(test);

You don't need any regex functionality for this, so you should use the non-regex version String.replace(CharSequence, CharSequence) : 您不需要任何正则表达式功能,因此您应该使用非正则表达式版本String.replace(CharSequence,CharSequence)

String test = "select * from blah *asdf";
test = test.replace("*", "\\*");
System.out.println(test);

For those of you keeping score at home, and since understanding the answer may be helpful to someone else... 对于那些在家里得分的人,并且因为理解答案可能对其他人有帮助...

String test = "select * from blah *asdf";
test = test.replaceAll("\\*", "\\\\*");
System.out.println(test);

works because you must escape the special character * in order to make the regular expression happy. 因为必须转义特殊字符*才能使正则表达式满意。 However, \\ is a special character in a Java string, so when building this regex in Java, you must also escape the \\ , hence \\\\* . 但是, \\是Java字符串中的特殊字符,因此在Java中构建此正则表达式时,还必须转义\\ ,因此\\\\*

This frequently leads to what amounts to double-escapes when putting together regexes in Java strings. 在Java字符串中放置正则表达式时,这经常会导致双重转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM