Reputation: 788
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?
Upvotes: 1
Views: 102
Reputation: 785196
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:
.replaceAll("\\bD#", "y")
before other replaceAll
that is replacing all words with D
with x
.\\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");
Upvotes: 1