如何从字符串中删除除破折号和空格字符外的所有非字母数字字符?
当前回答
基于这个问题的答案,我创建了一个静态类并添加了这些。我觉得可能对某些人有用。
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);
它更简单,所以我认为它更好!
正则表达式为[^\w\s\-]*:
使用\s而不是space()更好,因为文本中可能有制表符。
使用Regex有一个更简单的方法。
private string FixString(string str)
{
return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}
下面是一个使用@ata answer作为灵感的扩展方法。
"hello-world123, 456".MakeAlphaNumeric(new char[]{'-'});// yields "hello-world123456"
或者如果您需要除连字符以外的其他字符…
"hello-world123, 456!?".MakeAlphaNumeric(new char[]{'-','!'});// yields "hello-world123456!"
public static class StringExtensions
{
public static string MakeAlphaNumeric(this string input, params char[] exceptions)
{
var charArray = input.ToCharArray();
var alphaNumeric = Array.FindAll<char>(charArray, (c => char.IsLetterOrDigit(c)|| exceptions?.Contains(c) == true));
return new string(alphaNumeric);
}
}
你可以试试:
string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");
s是你的弦。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和