正则表达式去除串双/三逗号 [英] Regex removing double/triple comma in string

查看:116
本文介绍了正则表达式去除串双/三逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析字符串,所以结果应该这样的输出:

I need to parse a string so the result should output like that:

"abc,def,ghi,klm,nop"

不过,我收到可能看起来更像是字符串:

But the string I am receiving could looks more like that:

",,,abc,,def,ghi,,,,,,,,,klm,,,nop"

问题的关键是,我不知道提前很多逗号分隔怎样的话。结果
是有一个正则表达式我可以在C#中使用,可以帮助我解决这个问题呢?

The point is, I don't know in advance how many commas separates the words.
Is there a regex I could use in C# that could help me resolve this problem?

推荐答案

您可以使用,{ 2,} 表达式匹配2个或多个逗号任何出现,然后用一个逗号替换它们。

You can use the ,{2,} expression to match any occurrences of 2 or more commas, and then replace them with a single comma.

您可能会需要一个修剪呼叫有太多,以消除任何前导或尾随逗号从 Regex.Replace 通话遗留下来的。 (这可能是有一些方法只有一个正则表达式替换做到这一点,但没有立即浮现在脑海。)

You'll probably need a Trim call in there too, to remove any leading or trailing commas left over from the Regex.Replace call. (It's possible that there's some way to do this with just a regex replace, but nothing springs immediately to mind.)

string goodString = Regex.Replace(badString, ",{2,}", ",").Trim(',');

这篇关于正则表达式去除串双/三逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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