我正在使用asp.net 4和c#.
我有一个字符串,可以包含:
示例字符串:
#Hi this is rèally/ special strìng!!!
Run Code Online (Sandbox Code Playgroud)
我想要:
a)删除所有特殊字符,例如:
Hi this is rèally special strìng
Run Code Online (Sandbox Code Playgroud)
b)将所有重音字母转换为非重音字母,例如:
Hi this is really special string
Run Code Online (Sandbox Code Playgroud)
c)删除所有空格并用短划线( - )替换主题,如:
Hi-this-is-really-special-string
Run Code Online (Sandbox Code Playgroud)
我的目标是创建一个适合URL路径的字符串,以获得更好的SEO.
任何想法如何使用正则表达式或其他技术?
感谢您对此的帮助!
类似于mathieu的答案,但更多的定制为您提出要求.此解决方案首先从输入字符串中删除特殊字符和变音符号,然后用短划线替换空格:
string s = "#Hi this is rèally/ special strìng!!!";
string normalized = s.Normalize(NormalizationForm.FormD);
StringBuilder resultBuilder = new StringBuilder();
foreach (var character in normalized)
{
UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory(character);
if (category == UnicodeCategory.LowercaseLetter
|| category == UnicodeCategory.UppercaseLetter
|| category == UnicodeCategory.SpaceSeparator)
resultBuilder.Append(character);
}
string result = Regex.Replace(resultBuilder.ToString(), @"\s+", "-");
Run Code Online (Sandbox Code Playgroud)
在ideone.com上查看它的实际操作.