replaceAll or regex java forward slash

Luis Gutierrez Paucar :

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 :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=104003&siteId=1