Alex Rivera | Logout

Regex to remove a specific repeated character

Asked 2011-02-24T23:44:09.513
15

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.

Example:

"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?

Edit
Report

1 Answer

26

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('-');
answered 2011-02-24T23:52:27.167

Your Answer