Java replaceAll() regex does not work [duplicate]

心不动则不痛 提交于 2019-12-28 07:07:06

问题


I'm trying to replace all special characters with a "%", like:

"123.456/789" -> "123%465%798"

my regular expression is:

[^a-zA-Z0-9]+

In online tools* it works perfecly, but in java

s.replaceAll("[^a-zA-Z0-9]+", "%");

strings remain untouched.

*I tried: http://www.regexplanet.com/ http://regex101.com/ and others


回答1:


Strings are immutable. You forgot to reassign new String to the s variable :)

s = s.replaceAll("[^a-zA-Z0-9]+", "%");
 // ^ this creates a new String



回答2:


replaceAll() like all methods in String class, DO NOT modify String on which you invoke a method. This is why we say that String is immutable object. If you want to 'modify' it, you need to do

s = s.replaceAll("[^a-zA-Z0-9]+", "%");

In fact you don't modify String s. What happens here is that new String object is returned from a function. Then you assign its reference to s.




回答3:


You can't change a String, instead replaceAll returns a new value. so you should use it like this

String newStr = s.replace(...)



回答4:


Working code as per your expectations :)

import java.util.regex.Pattern;


public class Regex {

    public static void main(String[] args) {
        String s = "123.456/789";
        Pattern p = Pattern.compile("[^a-zA-Z0-9]+");
        String newStr = s.replaceAll("[^a-zA-Z0-9]+", "%");
        System.out.println(s + " -> " + newStr);
    }
}

Output : 123.456/789 -> 123%456%789



来源:https://stackoverflow.com/questions/21436517/java-replaceall-regex-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!