如何在包含dot的java中替换String? [英] How to replace a String in java which contains dot?

查看:92
本文介绍了如何在包含dot的java中替换String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要替换包含空格和句点的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); 

但这导致:


customerName Mr.RajKumar

customerName Mr.RajKumar


customerName

customerName

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

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

推荐答案

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

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.]", "");

这篇关于如何在包含dot的java中替换String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆