user567679 user567679 - 1 year ago 72
Java Question

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)
String sa = "LTD.";
sa = sa.replaceAll("L.","LE");
sa = sa.replaceAll("LTD.","LTD&#8901");
catch (Exception e)


Output should be: LTD&#8901

But output is showing: LED.

Answer Source

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:

Compile and run this code here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download