MariaH
MariaH

Reputation: 341

Insert a whitespace after comma, period and other punctuation marks

In Java, what is the best way to fix the missing whitespace after some punctuation marks like:

, . ; : ? !

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, of a string, that needs? to be fixed. by inserting: a whitespace; after punctuation marks."

It is clear that this does not work:

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

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

Upvotes: 4

Views: 10071

Answers (3)

hwnd
hwnd

Reputation: 70732

You can use a combination of Positive Lookbehind and Negative Lookahead.

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

Explanation:

The Positive Lookbehind asserts at the position that follows any of the select punctuation. The use of the Negative Lookahead says, at this position ( end of the string ), the following can not match.

(?<=           # look behind to see if there is:
  [,.!?;:]     #   any character of: ',', '.', '!', '?', ';', ':'
)              # end of look-behind
(?!            # look ahead to see if there is not:
  $            #   before an optional \n, and the end of the string
)              # end of look-behind

Working Demo

Upvotes: 9

Federico Piazza
Federico Piazza

Reputation: 31035

You have to add $0 to your replace expression, you can use:

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

It will replace your matched regex with that content plus a space.

Btw, if you want ensure that you don't have multiple whitespaces you can do:

example = example.replaceAll("[,.!?;:]", "$0 ").replaceAll("\\s+", " "); 

Will convert:

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

To:

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

Upvotes: 7

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You can use this with look ahead assertion to prevent adding extra space to the empty space, and match all the non character and add space after them.:

solution:

     String example = "This is!just an:example,of a string,that needs?to be fixed.by inserting:a whitespace;after punctuation marks.";
     example = example.replaceAll("(?!\\s)\\W", "$0 ");
     System.out.println(example);

result:

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

Upvotes: 1

Related Questions