Java: Remove full stop in string

2019-02-27 12:08发布

问题:

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.

Is it possible to delete only the full stops? Thank you for your answers!

回答1:

replaceAll takes a regular expressions as an argument, and . in a regex means "any character".

You can use replace instead:

inpt = inpt.replace(".", "");

It will remove all occurences of ..



回答2:

Don't use replaceAll(), use 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 both replace 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.



回答3:

String#replaceAll(String, String) takes a regex. The dot is a regex meta character that will match anything.

Use

inpt = inpt.replace(".", "");

it will also replace every dot in your inpt, but treats the first parameter as a literal sequence, see JavaDoc.

If you want to stick to regex, you have to escape the dot:

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


回答4:

I think you have to mask the dot

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


回答5:

replaceAll use a regex, please use the following:

inpt = inpt.replaceAll("\\.", "")


标签: java replace