How to handle character "#" in Regex?

elyar abad :

I'm trying the code below:

String txt = "D D#";
String txt2 = txt.replaceAll("\\bD\\b", "x").replaceAll("\\bD#\\b", "y");

I'm waiting to get "x y", but it returns "x x#". What could be the solution?

anubhava :

As per your edited question, you want to do replacements with word boundaries.

You may use this code to fix:

String txt = "D D#";
String txt2 = txt.replaceAll("\\bD#", "y").replaceAll("\\bD\\b", "x");
//=> "x y"

Note the changes:

  1. Calling .replaceAll("\\bD#", "y") before other replaceAll that is replacing all words with D with x.
  2. Not using word boundary \\b after # since word boundary is not matched after a non-word character. \b is asserted for (^\w|\w$|\W\w|\w\W) positions.

Also note that you can also use replaceFirst instead of replaceAll and keep code as:

String txt2 = txt.replaceFirst("\\bD\\b", "x").replaceFirst("\\bD#", "y");

Guess you like

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