我需要替换包含空格和句点的String.我尝试过以下代码:
String customerName = "Mr. Raj Kumar";
customerName = customerName.replaceAll(" ", "");
System.out.println("customerName"+customerName);
customerName = customerName.replaceAll(".", "");
System.out.println("customerName"+customerName);
Run Code Online (Sandbox Code Playgroud)
但结果是:
customerName Mr.RajKumar
和
顾客姓名
我从第一个SOP获得了正确的客户名称,但是从第二个SOP我没有得到任何价值.
jlo*_*rdo 29
逃避点,否则它将匹配任何角色.这种转义是必要的,因为replaceAll()将第一个参数视为正则表达式.
customerName = customerName.replaceAll("\\.", "");
Run Code Online (Sandbox Code Playgroud)
你可以用一个陈述完成整个事情:
customerName = customerName.replaceAll("[\\s.]", "");
Run Code Online (Sandbox Code Playgroud)
小智 6
在您的代码中使用它只是为了删除句点
customerName = customerName.replaceAll("[.]","");
Run Code Online (Sandbox Code Playgroud)