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?
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]+", "")
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.
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('-');
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");
}
}
}
string tidyText = Regex.Replace(originalText, "^-+|(?<=-)-+|-+$", "");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With