Java replaceAll() regex does not work [duplicate]

一笑奈何 提交于 2019-11-28 02:18:51

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

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.

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

String newStr = s.replace(...)

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

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