'Replace all but last instance of specified character

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.



Solution 1:[1]

Another approach, which may perform much faster than a 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 gist is that it will replace all occurrences of "," with an empty string between the first character and the index of the last ",".

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

Solution 2:[2]

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

Solution 3:[3]

A none regex approach:

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

Solution 4:[4]

An uglier, yet valid alternative approach:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Mark Byers
Solution 3 Tim Schmelter
Solution 4 NoAlias