Replace all Special Characters in a string IN C#

2019-05-22 14:00发布

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

3条回答
地球回转人心会变
2楼-- · 2019-05-22 14:40

Try the pattern: "[^a-zA-Z]+" - i.e. replace one-or-more non-alpha (you might allow numeric, though?).

查看更多
Emotional °昔
3楼-- · 2019-05-22 14:41

Wouldn't this work?

string pattern = "[^a-zA-Z]+";
查看更多
老娘就宠你
4楼-- · 2019-05-22 14:44

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();

        }
查看更多
登录 后发表回答