Unknown User
Unknown User

Reputation: 356

Java RegExp Underscore

I want to replace content (double underscores left and right, see code) in a given string, but can't get it to work. So something like this:

String test = "Hello! This is the content: __content__";
test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);

So the output should be: "Output: Hello! This is the content: Yeah!" The regular expression in the first parameter of the replaceAll simply is wrong, but I don't know the correct one. Anyone knows how?

Upvotes: 2

Views: 85

Answers (3)

almightyGOSU
almightyGOSU

Reputation: 3739

It should be:

String test = "Hello! This is the content: __content__";
test = test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);

replaceAll returns the resulting string!

Upvotes: 1

tibtof
tibtof

Reputation: 7957

In Java strings are immutable, so replaceAll doesn't modify the string, but returns a new String.

Upvotes: 2

anubhava
anubhava

Reputation: 785146

You forgot to assign return value of replaceAll back to original string. replaceAll (or any other string method) doesn't change the original string:

String test = "Hello! This is the content: __content__";
test = test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);

btw you don't even need a regex here, just use replace:

test = test.replace("__content__", "Yeah!");

Upvotes: 2

Related Questions