Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a String in java which contains dot?

Tags:

java

string

I need to replace a String which contains white space and periods. I have tried with the following code:

String customerName = "Mr. Raj Kumar";

customerName = customerName.replaceAll(" ", "");
System.out.println("customerName"+customerName);

customerName = customerName.replaceAll(".", "");
System.out.println("customerName"+customerName); 

but this results in:

customerName Mr.RajKumar

And

customerName

I am getting the correct customer name from the first SOP, but from second SOP I am not getting any value.

like image 807
Raghupathiraja Avatar asked Dec 29 '12 08:12

Raghupathiraja


2 Answers

escape the dot, or else it will match any character. This escaping is necessary, because replaceAll() treats the first paramter as a regular expression.

customerName = customerName.replaceAll("\\.", "");

You can do the whole thing with one statement:

customerName = customerName.replaceAll("[\\s.]", "");
like image 162
jlordo Avatar answered Oct 03 '22 23:10

jlordo


use this in your code just for remove periods

customerName = customerName.replaceAll("[.]","");
like image 30
Manish Nagar Avatar answered Oct 03 '22 23:10

Manish Nagar