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⋅");
System.out.println(sa);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output should be: LTD⋅
But output is showing: LED.
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⋅");
More info on java regex: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Compile and run this code here.