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:
- Calling
.replaceAll("\\bD#", "y")
before otherreplaceAll
that is replacing all words withD
withx
. - 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");