Search code examples
javareplaceall

replaceAll in java giving wrong output


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.


Solution

  • 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.