[英]Java Regular expression special characters
I want to replace xx*
with x
. 我想用
x
代替xx*
。
I tried string.replaceAll("xx*", "x");
我尝试过
string.replaceAll("xx*", "x");
but in regex *
is special so I need to give a \\*
but to give a \\
in java i need to give \\\\
但是在正则表达式中
*
是特殊的,所以我需要给一个\\*
但在Java中给一个\\
我需要给\\\\
==> finally it should work with string.replaceAll("xx\\\\*", "x");
==>最后,它应该可以使用
string.replaceAll("xx\\\\*", "x");
but when the string contains xx*
the above statement fails in replacing xx*
with x
但是当字符串包含
xx*
,以上语句无法将xx*
替换为x
You have to reassign the result of the replaceAll()
call to the string variable - that method returns a new string as opposed to modifying the string you call it on. 您必须将
replaceAll()
调用的结果重新分配给字符串变量-该方法返回一个新字符串,而不是修改您调用它的字符串。
Don't use replaceAll()
!! 不要使用
replaceAll()
! Use replace()
when dealing with literal strings: 处理文字字符串时,请使用
replace()
:
string = string.replace("xx*", "x");
Strings are immutable. 字符串是不可变的。 Assign the result of
replaceAll
to the original value 将
replaceAll
的结果分配给原始值
string = string.replaceAll("xx\\*", "x");
string.replaceAll("xx\\\\*", "x")
will not change the given string, as strings are immutable in Java. string.replaceAll("xx\\\\*", "x")
不会更改给定的字符串,因为字符串在Java中是不可变的。 You need to use the returned value, for instance by assigning it back to the original variable: string = string.replaceAll("xx\\\\*", "x")
您需要使用返回的值,例如,将其分配回原始变量:
string = string.replaceAll("xx\\\\*", "x")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.