Java – insert spaces after commas, periods, and other punctuation marks

In Java, the best way to fix missing spaces after some punctuation is:

,. ; : ? !

For example:

String example = "This is!just an:example,of a string,that needs?to be fixed.by inserting:a whitespace;after punctuation marks.";

The output should be:

"This is! just an: example,that needs? to be fixed. by inserting: a whitespace; after punctuation marks."

Obviously, this doesn't work:

example = example.replaceAll("[,.!?;:]"," ");

So I'm looking for a solution waiting for your help thank you!!

Solution

You must add $0 to your replacement expression. You can use:

example = example.replaceAll("[,"$0 ");

It replaces the matching regular expression with that content and a space

By the way, if you want to make sure you don't have multiple spaces, you can do this:

example = example.replaceAll("[,"$0 ").replaceAll("\\s+"," ");

Convert to:

To:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>