Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 "½"?

like image 644
Johan Nordli Avatar asked Dec 19 '13 15:12

Johan Nordli


People also ask

What is replaceAll \\ s in Java?

The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.

What is the difference between Replace () and replaceAll ()?

The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)

How do you rewrite a string in Java?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.


2 Answers

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

like image 137
arshajii Avatar answered Oct 27 '22 08:10

arshajii


Because replaceAll takes a regular expression. That means . is interpreted as a wildcard that also matches 7 so that .5 matches 75. You can escape in regular expressions using \ but note that this is also a String which means you will have to escape twice: so replaceAll("\\.5", "½") will do what you wanted.

like image 23
Martin Ring Avatar answered Oct 27 '22 07:10

Martin Ring