Link to home
Start Free TrialLog in
Avatar of tmajor99
tmajor99

asked on

Regular Expression to check for spaces before and after a comma

need a regular expression that will check and remove a space before and after a comma and remove the comma if value is null following the comma.  

Data                   Expected Results
------------             --------------
CHN, USA             CHN,USA
CHN , USA            CHN,USA
CHN,USA              CHN,USA
CHN,                     CHN
CHN ,                    CHN
CHN , USA, LBB   CHN,USA,LBB
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of skullnobrains
skullnobrains

a comma as the last character of the text possibly followed by spaces

    /, *$/
If your regex engine supports typical replacement syntax, these should work:
s/\s*,\s*/,/g
s/,$//g

Open in new window


If your regex engine supports a little more, you could do:
s/\s*(?:(,)\s*(?=\S)|,\s*$)/$1/g

Open in new window

another short approach since the data does not contain spaces
s/ //g
s/,$//