3

I want to change the string "S/" to "S/." only whole word , I tried with Pattern.compile and Matcher.quoteReplacement. I didn't find the solution.

public static void main(String[] args) {
    String cadena = "Moneda Actual : S/";
    cadena = cadena.replaceAll("\\bS/\\b", "S/.");
    System.out.println(cadena);
}

This code print :

Moneda Actual : S/

I want to print :

Moneda Actual : S/.

So if original text is "Moneda Actual : S/." , the algorithm mustn't replace to "S/.."

Bohemian
  • 412,405
  • 93
  • 575
  • 722

1 Answers1

2

Use a negative look ahead:

cadena = cadena.replaceAll("\\bS/(?!\\.)", "S/.");

The negative look ahead asserts (without consuming) that the next character is not a dot.

This will also work then "S/" occurs at the end of the String.

——

There is no word boundary after a slash and before a dot. Word boundaries are between “word” characters (letters, number and the underscore) and non-“word” characters. Not between whitespace and non-whitespace.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Great solution, also takes care of "S\.S\S\S\." – Coder-Man Jul 27 '18 at 22:20
  • 2
    @Wow `\b` (coded as `"\\b"` in a String literal) is a “word boundary”. It will prevent `"XS/"` from matching. See [this answer](https://stackoverflow.com/a/6664167/256196) for a full description. – Bohemian Jul 28 '18 at 00:56