Replace all but the last instance of the specified character

If I have a string like

10,000kg crane,21 ,

how should i remove all the commas but the last ones to get

10000kg crane,21 ?

I think this is a regex problem.

+4
source share
4 answers

Another approach that can work much faster than RegEx solution:

 Dim s As String = "10,000kg crane,21" Dim result As String = New StringBuilder(s).Replace(",", String.Empty, 0, s.LastIndexOf(","c)).ToString() 

The bottom line is that it will replace all occurrences of "," with an empty string between the first character and the index of the last ",".

I completed some of the steps and the proposed RegEx solution 1,000,000 times each; on my laptop, without compiling RegEx, this solution is about seven (7) times faster. If you compile RegEx, it's still about twice as fast.

+5
source

This can be done using regular expressions using the lookahead expression. You want to replace commas that have at least one comma after them. The only comma for which this look looks unsuccessful is the last.

Try the following:

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

See how it works on the Internet: ideone

+6
source

There is no regex approach:

 Dim text = "10,000kg crane,21" Dim parts = text.Split(","c).Reverse Dim result = String.Join("", parts.Skip(1).Reverse) & "," & parts.First 
+1
source

A uglier but valid alternative approach:

  Dim strResult As String = Replace(Mid(strTarget, 1, strTarget.LastIndexOf(",")), ",", String.Empty) & _ Microsoft.VisualBasic.Right(strTarget, Len(strTarget) - strTarget.LastIndexOf(",")) 
0
source

All Articles