Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式特殊字符_Java_Regex - Fatal编程技术网

Java正则表达式特殊字符

Java正则表达式特殊字符,java,regex,Java,Regex,我想用x替换xx* 我尝试了string.replaceAll(“xx*”,“x”) 但是在正则表达式中,*是特殊的,所以我需要给出一个\* 但是要在java中给出一个\,我需要给出\ ==>最后,它应该使用string.replaceAll(“xx\\*”,“x”) 但是当字符串包含xx*时,上述语句无法将xx*替换为x字符串是不可变的。将replaceAll的结果指定给原始值 string = string.replaceAll("xx\\*", "x"); 字符串是不可变的。将repla

我想用
x
替换
xx*

我尝试了
string.replaceAll(“xx*”,“x”)

但是在正则表达式中,
*
是特殊的,所以我需要给出一个
\*
但是要在java中给出一个
\
,我需要给出
\

==>最后,它应该使用
string.replaceAll(“xx\\*”,“x”)


但是当字符串包含
xx*
时,上述语句无法将
xx*
替换为
x

字符串是不可变的。将
replaceAll
的结果指定给原始值

string = string.replaceAll("xx\\*", "x");

字符串是不可变的。将
replaceAll
的结果指定给原始值

string = string.replaceAll("xx\\*", "x");

使用
string.replaceAll(“xx\\*”,“x”)
而不是
string.replaceAll(“xx\*”,“x”)

这很好用


现场演示。

使用
string.replaceAll(“xx\\\*”,“x”)
而不是
string.replaceAll(“xx\*”,“x”)

这很好用

实时演示。

string.replaceAll(“xx\\*”,“x”)
不会更改给定的字符串,因为字符串在Java中是不可变的。您需要使用返回的值,例如通过将其赋回原始变量:
string=string.replaceAll(“xx\\*”,“x”)
string.replaceAll(“xx\\*”,“x”)
不会更改给定的字符串,因为字符串在Java中是不可变的。您需要使用返回的值,例如通过将其赋回原始变量:
string=string.replaceAll(“xx\\*”,“x”)

  • 您必须重新分配
    replaceAll()
    调用字符串变量的结果-该方法返回一个新字符串,而不是修改调用它的字符串

  • 不要使用
    replaceAll()
    !!处理文字字符串时使用:

    string = string.replace("xx*", "x");
    
  • 您必须重新分配
    replaceAll()
    调用字符串变量的结果-该方法返回一个新字符串,而不是修改调用它的字符串

  • 不要使用
    replaceAll()
    !!处理文字字符串时使用:

    string = string.replace("xx*", "x");
    

  • 你肯定是说“xx\\*”?我试着打了三次。我想是StackOverflow的错误。谢谢你,伙计,我帮了大忙。你是说“xx\\*”?我试着打了三次。我想这是StackOverflow的一个bug。多谢老兄,我是非常乐于助人的+1,因为我是唯一一个意识到这个操作不需要基于正则表达式的解决方案的人。我想补充一点:如果你真的需要使用replaceAll()及其正则表达式,但不想分析和转义第一个参数,那么你可以使用Pattern.quote()方法,为你+1,让唯一一个意识到这个操作不需要基于正则表达式的解决方案的人。我想补充一点:如果您真的需要使用replaceAll()及其正则表达式,但不想分析和转义第一个参数,那么可以使用Pattern.quote()方法