Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a comma with Regex in C#

Tags:

c#

.net

I encountered a problem with quite simple thing I guess, I want to replace each comma ',' in a string except for the ones that are surrounded by digits. Examples:

hey, world -> hey,\nworld
hey  ,  world -> hey,\nworld
they are simple, but now also:
hey,world -> hey,\nworld
hey),world -> hey),\nworld
(1,2) -> (1,2) << no change :P 

I tried it with different Regexes and I can't really get it working as easily as I'd like to. Matching the commas that I need is quite easy but the problem is that I thought I can do it this way:

Regex.Replace(input, @"[^\d]\s*,\s*[^\d]", ",\n");

it works cool but it changes my:

hey,world into: he,\norld

I'd be glad if you could help me figure that out :)

Regards, Andrew

like image 405
Andrzej Czerwoniec Avatar asked Dec 05 '25 03:12

Andrzej Czerwoniec


1 Answers

This uses negative lookbehind (?<!...) and negative lookahead (?!...) to check for the presence of digits.

(?<![0-9])\s*,\s*|\s*,\s*(?![0-9])

It means: not preceded by digits OR not followed by digits. So the only failure case is: preceded by digits AND followed by digits.

Be aware that \d is different than [0-9]. ԱԲԳԴԵԶԷԸԹ0123456789 are \d (and many others) (they are Armenian numerals), while 0123456789 are [0-9]

My original regex was TOTALLY WRONG! Because it was: not-preceded by digits AND not-followed by digits, while the request was: non-preceded by digits OR not followed by digits.

like image 126
xanatos Avatar answered Dec 06 '25 16:12

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!