0

I have an input text and a searchterm.

intput = "Hello (A) World" searchTerm = "(A)";

I want to write a method that remove the searchTerm from input.

My code.

    public String replaceText(String input, String replacement) {
      return input.replaceAll(Pattern.quote(replacement), "");
     }

    String result = replaceText("Hello (A) World", "(A)");
    System.out.println(result);

The result here is "Hello__World" with two whitespace. How I can modify my method to have a result "Hello World". With no extra whitespace left at the position of replacement?

Tristate
  • 1,498
  • 2
  • 18
  • 38

3 Answers3

3
public String replaceText(String input, String replacement) {
    String patternString = "\\s*" + Pattern.quote(replacement) + "\\s*";
    return input.replaceAll(patternString, " ").trim();
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

You can chain replaceAll's. It is often easier to read when they are fragmented.

String result = "Hello (A) World".replaceAll("\(A\)", "").replaceAll(" ", " ");

0
public String replaceText(String input, String replacement) {
        return input.replace(input.contains(replacement + " ") ? replacement + " " : replacement, "");
}
AZoG
  • 1
  • 2