正则表达式从字符串中删除所有特殊字符? [英] Regex to remove all special characters from string?

查看:156
本文介绍了正则表达式从字符串中删除所有特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全不能经常EX pressions的,所以我需要一个问题一些帮助,我认为的最好办法是使用常规的前pressions来解决。

I'm completely incapable of regular expressions, and so I need some help with a problem that I think would best be solved by using regular expressions.

我在C#中的字符串列表:

I have list of strings in C#:

List<string> lstNames = new List<string>();
lstNames.add("TRA-94:23");
lstNames.add("TRA-42:101");
lstNames.add("TRA-109:AD");

foreach (string n in lstNames) {
  // logic goes here that somehow uses regex to remove all special characters
  string regExp = "NO_IDEA";
  string tmp = Regex.Replace(n, regExp, "");
}

我需要能够遍历该列表并没有任何特殊的字符返回每个项目。例如,项目之一将是TRA9423,项目二将是TRA42101和第三项是TRA109AD。

I need to be able to loop over the list and return each item without any special characters. For example, item one would be "TRA9423", item two would be "TRA42101" and item three would be TRA109AD.

有一个常规的前pression可以做到这一点给我吗?

Is there a regular expression that can accomplish this for me?

此外,列表中包含超过4000个项目,所以我需要在搜索和替换为高效快捷如果可能的话。

Also, the list contains more than 4000 items, so I need the search and replace to be efficient and quick if possible.

在此先感谢,我收到任何帮助。

Thanks in advance for any help that I receive on this.

编辑:
对不起,我应该已经指定了A-Z身边的任何字符,A-Z和0-9是在我的情况特殊。

Sorry, I should have specified that any character beside a-z, A-Z and 0-9 is special in my circumstance.

推荐答案

这真的取决于你的特殊字符定义。我发现一个白名单,而不是黑名单是在大多数情况下,最好的办法:

It really depends on your definition of special characters. I find that a whitelist rather than a blacklist is the best approach in most situations:

tmp = Regex.Replace(n, "[^0-9a-zA-Z]+", "");

您应该小心与当前的做法,因为下面的两个项目将被转换为相同的字符串,因此将无法区分:

You should be careful with your current approach because the following two items will be converted to the same string and will therefore be indistinguishable:

"TRA-12:123"
"TRA-121:23"

这篇关于正则表达式从字符串中删除所有特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆