在 C# 中替换字符串中的所有特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1778879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:44:29  来源:igfitidea点击:

Replace all Special Characters in a string IN C#

c#replacecharacter

提问by Deepu

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

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

foo-bar-regular-expression-replace

How do I achieve this

我如何实现这一目标

Any help would be appreciated

任何帮助,将不胜感激

Thanks Deepu

谢谢迪普

回答by Marc Gravell

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

尝试以下模式:"[^a-zA-Z]+"- 即替换一个或多个非 alpha(不过,您可能允许使用数字?)。

回答by snarf

Wouldn't this work?

这行不通?

string pattern = "[^a-zA-Z]+";

回答by Richard

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

        }