Java replaceAll() regex does not work


This question already has an answer here:


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

Need Your Help

Validate multi-select fieid in php

javascript php jquery

I have one form with multi-select file i want to check if file is selecetd or not on click of submit button.Currently i am using following code,

Capistrano 'Bundle Not Found' Error During Deployment

ruby-on-rails shell environment-variables capistrano

When I run cap deploy:update I get the error below, indicating that bundle is not found. When I run echo $PATH from cap shell the /var/lib/gems/1.9.1/bin path which contains bundle is missing, howe...