-1

replaceAll is giving wrong output for the following code:-

package javaapplication3;

public class JavaApplication3
{
    public static void main(String[] args)
    {
        try
        {
            String sa = "LTD.";
            sa = sa.replaceAll("L.","LE");
            sa = sa.replaceAll("LTD.","LTD&#8901");
            System.out.println(sa);
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }

}

Output should be: LTD&#8901

But output is showing: LED.

Raptor
  • 187
  • 1
  • 2
  • 11
  • ReplaceAll uses regex. . Is any character, so there is no error. Works as designed. You can use replaceFirst if you don't need regex – YMomb Sep 04 '16 at 16:04

2 Answers2

2

Output is okay.

public static void main(String[] args) {
    String sa = "LTD.";
    sa = sa.replaceAll("L.", "LE"); // in regex . means any single character. So, "LT" is replaced. "LTD." is now "LED."
    sa = sa.replaceAll("LTD.", "LTD&#8901"); // "LED." doesn't have "LTD.". so no replace
    System.out.println(sa); // output "LED."
}

Use replace() instead.

public static void main(String[] args) {
    String sa = "LTD.";
    sa = sa.replace("L.", "LE");
    sa = sa.replace("LTD.", "LTD&#8901");
    System.out.println(sa);
}
Shahid
  • 2,288
  • 1
  • 14
  • 24
  • This will not work. replace takes a char, not a string. If you want to replace a string, you will have to use replaceAll and properly format the regex. – js441 Sep 04 '16 at 16:25
  • 1
    @js441 there are few overloaded `replace` methods. There is `replace(char, char)` like you mentioned, but there is also `replace(String, String)` which is basically version of `replaceAll(String, String)` which automatically escapes regex syntax. – Pshemo Sep 04 '16 at 16:36
  • 1
    @Pshemo, just realised there is a replace(CharSequence, CharSequence). Which can be implicitly created from a string literal. So replace(String, String) will work. – js441 Sep 04 '16 at 16:42
0

replaceAll takes a regular expression as it's first argument. In a regular expression, . matches any single character, so in the first replaceAll statement, LT is replaced with LE. You can fix this by escaping the . with \\.

 sa = sa.replaceAll("L\\.","LE");
 sa = sa.replaceAll("LTD\\.","LTD&#8901");

More info on java regex: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Compile and run this code here.

js441
  • 1,134
  • 8
  • 16