user567679 user567679 - 3 months ago 8
Java Question

replaceAll in java giving errors

replaceAll is giving errors 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.

Answer

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.

Comments