Replace all but last instance of specified character

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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.

回答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.



回答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



回答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


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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!