[英]How to replace a String in java which contains dot?
I need to replace a String which contains white space and periods. 我需要替换包含空格和句点的String。 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
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. 我从第一个SOP获得了正确的客户名称,但从第二个SOP我没有得到任何价值。
escape the dot, or else it will match any character. 逃避点,否则它将匹配任何角色。 This escaping is necessary, because replaceAll() treats the first paramter as a regular expression.
这种转义是必要的,因为replaceAll()将第一个参数视为正则表达式。
customerName = customerName.replaceAll("\\.", "");
You can do the whole thing with one statement: 你可以用一个陈述完成整个事情:
customerName = customerName.replaceAll("[\\s.]", "");
在代码中使用它只是为了删除句点
customerName = customerName.replaceAll("[.]","");
您可以简单地使用str.replace(“。”,“”)并且它将替换所有出现的点,记住只有一个区别在于替换和替换所有,后来使用正则表达式作为输入字符串,其中第一个使用简单字符序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.