Dodi
Dodi

Reputation: 2269

Insert space between each punctuation mark

I have a string and before and after each punctuation mark I want to insert a space like so

aaa , bbb . Hello ! here . I tried using the replaceAll method, I wanted something similar to:

String result = myStr.replaceAll("\\p{Punct}", "\s\\p{Punct}\s");

but since the second argument has to be a String, this does not work. Is there any way this could be accomplished using a regular expression ? Or I have to capture the punctuation mark separately and then replace it ?

Upvotes: 1

Views: 641

Answers (2)

Quinn
Quinn

Reputation: 4504

You could match each punctuation mark, and replace with " $0 ":

String input = "aaa,bbb.Hello!here.";
String result = input.replaceAll("[.!?\\-]", " $0 ");
System.out.println (result);

Output:

aaa , bbb . Hello ! here . 

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

You need to use backreferences and literals in the replacement:

String result = myStr.replaceAll("\\p{Punct}", " $0 ");

Or (if you want to wrap a sequence of punctuation symbols):

String result = myStr.replaceAll("\\p{Punct}+", " $0 ");

See the demo below:

String s = "aaa,fgh!edrf.";
String result = s.replaceAll("\\p{Punct}", " $0 ");
System.out.println(result); // => aaa , fgh ! edrf . 
System.out.println("aaa,,,fgh!!!edrf???".replaceAll("\\p{Punct}+", " $0 "));
// => aaa ,,, fgh !!! edrf ??? 

Upvotes: 1

Related Questions