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 "½"?
The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
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.
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)
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.
You're using replaceAll()
, which takes a regular expression. In regex-land, .
means "any character". Use replace()
instead, which works with literal strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With