OBL*_*OBL 16 c# special-characters
我想从字符串中删除所有特殊字符.允许的字符是AZ(大写或小写),数字(0-9),下划线(_),空格(),百分比(%)或点号(.).
我试过这个:
StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') | c == '.' || c == '_' || c == ' ' || c == '%')
{ sb.Append(c); }
}
return sb.ToString();
Run Code Online (Sandbox Code Playgroud)
还有这个:
Regex r = new Regex("(?:[^a-z0-9% ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
return r.Replace(input, String.Empty);
Run Code Online (Sandbox Code Playgroud)
但似乎没有任何效果.任何帮助将不胜感激.
谢谢!
San*_*ath 44
Regex.Replace(input, "[^a-zA-Z0-9% ._]", string.Empty)
Run Code Online (Sandbox Code Playgroud)
Yur*_*ich 15
您可以简化第一种方法
StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
if (Char.IsLetterOrDigit(c) || c == '.' || c == '_' || c == ' ' || c == '%')
{ sb.Append(c); }
}
return sb.ToString();
Run Code Online (Sandbox Code Playgroud)
这似乎通过了简单的测试.您可以使用LINQ缩短它
return new string(
input.Where(
c => Char.IsLetterOrDigit(c) ||
c == '.' || c == '_' || c == ' ' || c == '%')
.ToArray());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37213 次 |
| 最近记录: |