Reputation: 7995
I have a newbie question about replaceAll
method on String. It works fine as long as the input does not contain any type of space (breaking/non-breaking etc).
How to sanitize the input so it covers all cases for special space characters and I can use something like this:
String replaced = replaced.replaceAll("my-test (2)", "test"); // not working
I tried various types of regex with \\s
, \u00A0
etc.
EDIT: I noticed that the braces are also causing some problems with replaceAll.
This is my case:
"my-value (2)".replaceAll("my-value (2)", "test);
Upvotes: 0
Views: 109
Reputation: 11
Instead of using replaceAll() method, you can use replace(CharSequence target, CharSequence replacement). This will remove all the occurrence of the given string with new one. EX.
String sub=s.replace("my-test (2)", "test");
Upvotes: 0
Reputation: 473
This code is not going to compile. which IDE are you using? You are not even initialize the variable replaced
and replaceAll()
method uses regular expression. change replaceAll()
to replace()
. Try something like this.
String replaced = "my-test (2)";
replaced = replaced.replace("my-test (2)", "test");
System.out.println(replaced);
Upvotes: 1
Reputation: 520978
I would use here:
String input = "my-value (2)";
String output = input.replaceAll("\\bmy-value\\s*\\(2\\)(?!\\S)", "test");
System.out.println(output);
This prints: test
Here is an explanation of the regex pattern:
\b word boundary
my-value match "my-value"
\s* zero or more whitespace characters
\(2\) match "(2)"
(?!\S) assert that what follows is either whitespace or the end of the input
Upvotes: 4
Reputation: 49
First argument of replaceAll() method is regex. "my-test (2)"
contains regex group "(2)".
so try to use something like replaced.replaceAll("my-test \\(2\\)", "test"));
Upvotes: 0