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.
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.
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.
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
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
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(","))