Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to remove a specific repeated character

Tags:

c#

regex

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?

like image 434
Dismissile Avatar asked Feb 24 '11 23:02

Dismissile


People also ask

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do you find a repeating character?

Simple Solution: The solution is to run two nested loops. Start traversing from left side. For every character, check if it repeats or not. If the character repeats, increment count of repeating characters.


3 Answers

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('-');
like image 136
KeithS Avatar answered Oct 07 '22 03:10

KeithS


For this specific problem, I'd probably not use a regex. Instead, I'd probably use a combination of String.Split and String.Join, which will be simpler and likely faster:

Like this:

string.Join("-", s.Split(new char[] {'-'}, StringSplitOptions.RemoveEmptyEntries));

With tests:

using System;
class Program
{
    static string RemoveDashes(string s)
    {
        return string.Join("-", s.Split(new char[] { '-' }, 
                            StringSplitOptions.RemoveEmptyEntries));
    }
    static void Main(string[] args)
    {
        Tuple<string, string>[] tests = new Tuple<string,string> [] 
        {
            new Tuple<string, string> ("a--b-c-", "a-b-c"),
            new Tuple<string, string> ("-a--b-c-", "a-b-c"),
            new Tuple<string, string> ("--a--b--c--", "a-b-c"),
        };
        foreach (var t in tests)
        {
            string s = RemoveDashes(t.Item1);
            Console.WriteLine("{3}: {0} => Expected: {1}, Actual: {2}", 
                        t.Item1, t.Item2, s, s == t.Item2 ? "PASS" : "FAIL");
        }
    }
}
like image 35
Justin Grant Avatar answered Oct 07 '22 03:10

Justin Grant


string tidyText = Regex.Replace(originalText, "^-+|(?<=-)-+|-+$", "");
like image 41
LukeH Avatar answered Oct 07 '22 03:10

LukeH