0

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);
1
  • What is the expected output given the input my-test (2) ? Commented Jun 2, 2020 at 9:14

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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"));

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.