Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all but last instance of specified character

Tags:

regex

vb.net

If I have a string like

10,000kg crane,21

how should I strip all commas but the last to get

10000kg crane,21

I'm thinking this is a regular expression problem.

like image 848
Thalecress Avatar asked Aug 24 '12 21:08

Thalecress


1 Answers

It can be done with regular expressions by using a lookahead assertion. You want to replace the commas that have at least one comma after them. The only comma for which this lookahead will fail is the last one.

Try this:

s = Regex.Replace(s, ",(?=.*?,)", "")

See it working online: ideone

like image 88
Mark Byers Avatar answered Oct 22 '22 20:10

Mark Byers