Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all Special Characters in a string IN C#

I would like to find all special characters in a string and replace with a Hyphen (-)

I am using the below code

string content = "foo,bar,(regular expression replace) 123";    
string pattern = "[^a-zA-Z]"; //regex pattern 
string result  = System.Text.RegularExpressions.Regex.Replace(content,pattern, "-"); 

OutPut

foo-bar--regular-expression-replace----

I am getting multiple occurrence of hyphen (---) in the out put.

I would like to get some thing like this

foo-bar-regular-expression-replace

How do I achieve this

Any help would be appreciated

Thanks Deepu

like image 242
Deepu Avatar asked Dec 31 '25 07:12

Deepu


1 Answers

why not just do this:

public static string ToSlug(this string text)
        {
            StringBuilder sb = new StringBuilder();
            var lastWasInvalid = false;
            foreach (char c in text)
            {
                if (char.IsLetterOrDigit(c))
                {
                    sb.Append(c);
                    lastWasInvalid = false;
                }
                else
                {
                    if (!lastWasInvalid)
                        sb.Append("-");
                    lastWasInvalid = true;
                }
            }

            return sb.ToString().ToLowerInvariant().Trim();

        }
like image 104
Richard Avatar answered Jan 01 '26 20:01

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!