Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - inserting space after comma only if succeeded by a letter or number

Tags:

java

regex

In Java I want to insert a space after a String but only if the character after the comma is succeeded by a digit or letter. I am hoping to use the replaceAll method which uses regular expressions as a parameter. So far I have the following:

String s1="428.0,chf";
s1 = s1.replaceAll(",(\\d|\\w)",", ");   

This code does successfully distinguish between the String above and one where there is already a space after the comma. My problem is that I can't figure out how to write the expression so that the space is inserted. The code above will replace the c in the String shown above with a space. This is not what I want.

s1 should look like this after executing the replaceAll: "428.0 chf"

like image 576
Elliott Avatar asked Feb 18 '23 21:02

Elliott


1 Answers

s1.replaceAll(",(?=[\da-zA-Z])"," ");  

(?=[\da-zA-Z]) is a positive lookahead which would look for a digit or a word after ,.This lookahead would not be replaced since it is never included in the result.It's just a check

NOTE

\w includes digit,alphabets and a _.So no need of \d.

A better way to represent it would be [\da-zA-Z] instead of \w since \w also includes _ which you do not need 2 match

like image 87
Anirudha Avatar answered Feb 27 '23 11:02

Anirudha