如何在包含dot的java中替换String?

我需要替换包含空格和句点的String。 我尝试过以下代码:

String customerName = "Mr. Raj Kumar"; customerName = customerName.replaceAll(" ", ""); System.out.println("customerName"+customerName); customerName = customerName.replaceAll(".", ""); System.out.println("customerName"+customerName); 

但这会导致:

customerName Mr.RajKumar

顾客姓名

我从第一个SOP获得了正确的客户名称,但是从第二个SOP我没有得到任何价值。

逃避点,否则它将匹配任何角色。 这种转义是必要的,因为replaceAll()将第一个参数视为正则表达式。

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

你可以用一个陈述完成整个事情:

 customerName = customerName.replaceAll("[\\s.]", ""); 

在代码中使用它只是为了删除句点

 customerName = customerName.replaceAll("[.]",""); 

您可以简单地使用str.replace(“。”,“”)并且它将替换所有出现的点,记住只有一个区别在于替换和替换所有,后来使用正则表达式作为输入字符串,其中第一个使用简单字符序列。