Java:删除字符串中的句号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14909112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Remove full stop in string
提问by IndexOutOfBoundsException
I want to delete all the full stops ( . ) in a string.
我想删除字符串中的所有句号 ( . )。
Therefore I tried: inpt = inpt.replaceAll(".", "");
,
but instead of deleting only the full stops, it deletes the entire content of the string.
因此我尝试了:inpt = inpt.replaceAll(".", "");
,但它不是只删除句号,而是删除字符串的全部内容。
Is it possible to delete only the full stops? Thank you for your answers!
是否可以只删除句号?谢谢您的回答!
回答by assylias
replaceAll
takes a regular expressions as an argument, and .
in a regex means "any character".
replaceAll
将正则表达式作为参数,.
在正则表达式中表示“任何字符”。
You can use replace
instead:
您可以replace
改用:
inpt = inpt.replace(".", "");
It will remove all occurences of .
.
它将删除所有出现的.
.
回答by Bohemian
Don't use replaceAll()
, use replace()
:
不要使用replaceAll()
,使用replace()
:
inpt = inpt.replace(".", "");
It is a common misconception that replace()
doesn't replace all occurrences, because there's a replaceAll()
method, but in fact bothreplace all occurrences. The difference between the two methods is that replaceAll()
matches on a regex (fyi a dot in regex means "any character", which explains what you were experiencing) whereas replace()
matches on a literal String.
这是一个普遍的误解,replace()
不会替换所有出现的事件,因为有一种replaceAll()
方法,但实际上两者都替换了所有出现的事件。这两种方法之间的区别在于replaceAll()
匹配正则表达式(仅供参考,正则表达式中的点表示“任何字符”,这解释了您遇到的情况)而replace()
匹配文字字符串。
回答by jlordo
String#replaceAll(String, String)
takes a regex. The dot is a regex meta character that will match anything.
String#replaceAll(String, String)
需要一个正则表达式。点是一个正则表达式元字符,可以匹配任何东西。
Use
利用
inpt = inpt.replace(".", "");
it will also replace every dot in your inpt
, but treats the first parameter as a literal sequence, see JavaDoc.
它还将替换 中的每个点inpt
,但将第一个参数视为文字序列,请参阅JavaDoc。
If you want to stick to regex, you have to escape the dot:
如果你想坚持使用正则表达式,你必须转义点:
inpt = inpt.replaceAll("\.", "");
回答by Festus Tamakloe
I think you have to mask the dot
我认为你必须掩盖点
inpt = inpt.replaceAll("\.", "");
回答by Joe
replaceAll
use a regex, please use the following:
replaceAll
使用正则表达式,请使用以下内容:
inpt = inpt.replaceAll("\.", "")