如何使用Regex.Replace从字符串中删除数字?


71

我需要使用Regex.Replace删除字符串中的所有数字和符号。

输入123- abcd33
示例:输出示例:abcd


2
您还希望删除“-”吗?这些不是数字...
jle

Answers:


133

请尝试以下操作:

var output = Regex.Replace(input, @"[\d-]", string.Empty);

\d标识符简单地匹配任何数字字符。


20

您可以使用类似LINQ的解决方案来代替正则表达式:

string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());

快速性能测试表明,这比使用正则表达式快大约五倍。


1
@SirDemon:是的,LINQ通常不是最快的选择,但是正则表达式的初始开销更大。对于短字符串操作,设置RegEx对象要比实际工作花费更长的时间。
Guffa

@Guffa你知道这是如何缩放的吗?可以说,在5万条记录中,我应该去RegEx吗?
阿诺德·维尔斯玛

1
@ArnoldWiersma:两者都应该很好地缩放,它们基本上都是线性的,因此没有令人讨厌的惊喜。我不能说出哪个会更快,您必须进行测试。
Guffa '16

4
或者new string(text.Where(char.IsLetter).ToArray());
SkorunkaFrantišek18年



2

作为字符串扩展:

    public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

用法:

"My text 1232".RemoveIntegers(); // RETURNS "My text "


0
text= re.sub('[0-9\n]',' ',text)

在python中安装正则表达式,然后重新执行以下代码。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.