【发布时间】:2021-08-20 18:43:00
【问题描述】:
我需要创建一个方法来删除除_ 之外的所有特殊字符。
显然下面的代码不好!
这确实显示了我需要的东西。
最好的方法是什么?
是否有一个正则表达式可以工作,但允许使用_?
public static string SanitizeImportName(string importName)
{
if (string.IsNullOrWhiteSpace(importName) == true)
{
throw new ArgumentNullException(nameof(importName));
}
return importName.Replace("!", string.Empty)
.Replace("@", string.Empty)
.Replace("#", string.Empty)
.Replace("$", string.Empty)
.Replace("%", string.Empty)
.Replace("^", string.Empty)
.Replace("&", string.Empty)
.Replace("*", string.Empty)
.Replace("(", string.Empty)
.Replace(")", string.Empty)
.Replace("-", string.Empty)
.Replace("+", string.Empty)
.Replace("=", string.Empty)
.Replace("/", string.Empty)
.Replace("\\", string.Empty)
.Replace("{", string.Empty)
.Replace("}", string.Empty)
.Replace("[", string.Empty)
.Replace("]", string.Empty)
.Replace("|", string.Empty)
.Replace(":", string.Empty)
.Replace(";", string.Empty)
.Replace("\"", string.Empty)
.Replace("'", string.Empty)
.Replace("<", string.Empty)
.Replace(">", string.Empty)
.Replace(",", string.Empty)
.Replace(".", string.Empty)
.Replace("?", string.Empty)
.Replace("~", string.Empty)
.Replace("`", string.Empty);
}
【问题讨论】:
-
Regex.Replace(importName, @"[!@#$...]+", string.Empty);
标签: c#