replaceAll
uses regex as first parameter that will need to be found and dot .
in regex is metacharacter which will match all characters except new line. So when you are using
s = s.replaceAll(".5", "½");
on "1.75"
.5
can match 75
(since .
matches all). So after such change
1.75
-- will become
1.½
(notice that 1.25
works correctly only because you used .25
before .5
)
To prevent such behaviour you need to escape dot. You can do it by
- placing
\
before it (remember that to create \
literal you need to write it as "\\"
) "\\."
,
- place it in character class
[.]
,
- surround it with
\Q
and \E
which represent start and end of quote \\Q.\\E
- surrounding with
\Q
and \E
can be also done with Pattern.quote(".")
- In case of Pattern instance while compiling you can add
Pattern.LITERAL
flag to make all metacharacters used in pattern literals.
If you want our entire pattern be simple literal you can use replace
instead of replaceAll
which will automatically use Pattern.LITERAL
flag and change all regex metacharacters into simple literals.
So you can try something like
return s.replaceAll("\\.25", "¼").replaceAll("\\.5", "½").replaceAll("\\.75", "¾");
or simpler
return s.replace(".25", "¼").replace(".5", "½").replace(".75", "¾");
s = s.replaceAll(Pattern.quote(".25"), "¼");
– Kidding