在一个字符串在C#替换所有特殊字符 [英] Replace all Special Characters in a string IN C#
本文介绍了在一个字符串在C#替换所有特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到所有的特殊字符的字符串,用连字符替换( - )
我使用下面的代码
字符串内容=富,酒吧,(正则表达式替换)123;
字符串模式=[^ A-ZA-Z]; //正则表达式
字符串结果= System.Text.RegularExpressions.Regex.Replace(内容,模式, - );
输出
富巴 - 正则表达式替换----
块引用>
我收到连字符多发(--- )在出把。
我想获得这样的
富,酒吧,有些事正则表达式替换
块引用>
我如何做到这一点。
任何帮助我们将不胜感激。
由于
Deepu
解决方案为什么不只是这样做:
公共静态字符串ToSlug(此字符串文本)
{
StringBuilder的SB =新的StringBuilder();
VAR lastWasInvalid = FALSE;
的foreach(文本字符C)
{
如果(char.IsLetterOrDigit(C))
{
sb.Append(C);
lastWasInvalid = FALSE;
}
,否则
{
如果
sb.Append( - )(lastWasInvalid!);
lastWasInvalid = TRUE;
}
}
返回sb.ToString()ToLowerInvariant()修剪()。
}
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
解决方案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(); }
这篇关于在一个字符串在C#替换所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文