正则表达式来移除特定字符重复 [英] Regex to remove a specific repeated character

查看:163
本文介绍了正则表达式来移除特定字符重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建在C#中,去除如果重复它一个特定的字符,所以它不是字符串的最后一个字符一个正则表达式

I would like to create a regex in C# that removes a specific character if it is repeated and so it is not the last character of the string.

例如:

"a--b-c-" => "a-b-c"
"-a-b--c" => "a-b-c"
"--a--b--c--" => "a-b-c"



我从来没有想要的 - 反复,我从来没有想这是第一个或最后一个我的性格字符串。我怎么能写一个正则表达式来做到这一点?

I never want the - repeated, and I never want it to be the first or last character of my string. How could I write a regex to do this?

推荐答案

大概最容易做的这两个步骤。首先替换一个或多个的每次出现 - 跟单 - ,然后修剪任何前导/尾随 -

Probably easiest to do this in two steps. First replace each occurrence of one or more "-" with a single "-", then trim any leading/trailing "-".

var reducedString = Regex.Replace(inputString, "-+", "-");

var finalString = reducedString.Trim('-');

这篇关于正则表达式来移除特定字符重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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