Search code examples
javaregexstringreplaceall

String replaceAll("¾") in java


I have really weird error in my java code and can not figure out what is wrong.

Let's say I have this code:

private void test()
{
    String test1 = replace("1.25");
    String test2 = replace("1.5");
    String test3 = replace("1.75");
}

private String replace(String s)
{
     s = s.replaceAll(".25", "¼");
     s = s.replaceAll(".5", "½");
     s = s.replaceAll(".75", "¾");
     return s;
}

Then the result will be:

test1 = "¼"

test2 = "½"

test3 = "½" ??????????

Can someone please explain why test3 becomes "½"?


Solution

  • You're using replaceAll(), which takes a regular expression. In regex-land, . means "any character". Use replace() instead, which works with literal strings.