Java 如何替换所有星号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3860049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace all asterisks?
提问by Tim
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.
这不起作用,添加转义反斜杠也不起作用。
回答by Tim
I figured it out
我想到了
String test = "select * from blah *asdf";
test = test.replaceAll("\*", "\\*");
System.out.println(test);
回答by RonU
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 字符串中的正则表达式组合在一起时,这通常会导致双重转义。
回答by Sean Patrick Floyd
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);