Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex removing double/triple comma in string

Tags:

c#

regex

I need to parse a string so the result should output like that:

"abc,def,ghi,klm,nop"

But the string I am receiving could looks more like that:

",,,abc,,def,ghi,,,,,,,,,klm,,,nop"

The point is, I don't know in advance how many commas separates the words.
Is there a regex I could use in C# that could help me resolve this problem?

like image 919
MissRaphie Avatar asked Jan 13 '10 14:01

MissRaphie


1 Answers

You can use the ,{2,} expression to match any occurrences of 2 or more commas, and then replace them with a single comma.

You'll probably need a Trim call in there too, to remove any leading or trailing commas left over from the Regex.Replace call. (It's possible that there's some way to do this with just a regex replace, but nothing springs immediately to mind.)

string goodString = Regex.Replace(badString, ",{2,}", ",").Trim(',');
like image 123
LukeH Avatar answered Nov 14 '22 18:11

LukeH