简体   繁体   English

Java正则表达式特殊字符

[英]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

  1. 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()调用的结果重新分配给字符串变量-该方法返回一个新字符串,而不是修改您调用它的字符串。

  2. 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")

Use string.replaceAll("xx\\\\*", "x"); 使用string.replaceAll("xx\\\\*", "x"); instead of string.replaceAll("xx\\*", "x"); 而不是string.replaceAll("xx\\*", "x");

This is working fine. 一切正常。

Live Demo here . 现场演示这里

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

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