如何从字符串中删除除破折号和空格字符外的所有非字母数字字符?
当前回答
基于这个问题的答案,我创建了一个静态类并添加了这些。我觉得可能对某些人有用。
public static class RegexConvert
{
public static string ToAlphaNumericOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z0-9]");
return rgx.Replace(input, "");
}
public static string ToAlphaOnly(this string input)
{
Regex rgx = new Regex("[^a-zA-Z]");
return rgx.Replace(input, "");
}
public static string ToNumericOnly(this string input)
{
Regex rgx = new Regex("[^0-9]");
return rgx.Replace(input, "");
}
}
这些方法可用于:
string example = "asdf1234!@#$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();
其他回答
我做了一个不同的解决方案,通过消除控制字符,这是我最初的问题。
这比列出所有“特别但不错”的字符要好得多
char[] arr = str.Where(c => !char.IsControl(c)).ToArray();
str = new string(arr);
它更简单,所以我认为它更好!
如果你用JS工作,这里有一个非常简洁的版本
myString = myString.replace(/[^A-Za-z0-9 -]/g, "");
想要速食吗?
public static class StringExtensions
{
public static string ToAlphaNumeric(this string self,
params char[] allowedCharacters)
{
return new string(Array.FindAll(self.ToCharArray(),
c => char.IsLetterOrDigit(c) ||
allowedCharacters.Contains(c)));
}
}
这将允许您指定您希望允许的字符。
使用Regex有一个更简单的方法。
private string FixString(string str)
{
return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}
将[^a-zA-Z0-9 -]替换为空字符串。
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
推荐文章
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- 使用正则表达式搜索和替换Visual Studio代码
- csproj文件中的“Service Include”是干什么用的?
- 如何使用try catch进行异常处理是最佳实践
- 使用split("|")按管道符号拆分Java字符串
- 替换字符串中第一次出现的模式