替换指定字符的最后一个实例之外的所有实例 [英] Replace all but last instance of specified character

查看:21
本文介绍了替换指定字符的最后一个实例之外的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类似的字符串

If I have a string like

10,000kg 起重机,21,

我应该如何去掉除最后一个逗号之外的所有逗号

how should I strip all commas but the last to get

10000kg 起重机,21?

我认为这是一个正则表达式问题.

I'm thinking this is a regular expression problem.

推荐答案

另一种可能比 RegEx 解决方案执行得更快的方法:

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

我做了一些运行此和建议的 RegEx 解决方案 1,000,000 次的基准测试;在我的笔记本电脑上,不编译 RegEx,这个解决方案大约快七 (7) 倍.如果你编译了 RegEx,它的速度仍然是原来的两倍.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆