C# 如何使用 Regex.Replace 从字符串中删除数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1657282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove numbers from string using Regex.Replace?
提问by Gold
I need to use Regex.Replace
to remove all numbers and signs from a string.
我需要使用Regex.Replace
从字符串中删除所有数字和符号。
Example input: 123- abcd33
Example output: abcd
示例输入:123- abcd33
示例输出:abcd
采纳答案by Noldorin
Try the following:
请尝试以下操作:
var output = Regex.Replace(input, @"[\d-]", string.Empty);
The \d
identifier simply matches any digit character.
的\d
标识符简单地匹配任何数字字符。
回答by Darin Dimitrov
var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);
回答by Guffa
You can do it with a LINQ like solution instead of a regular expression:
您可以使用类似 LINQ 的解决方案而不是正则表达式来实现:
string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
A quick performance test shows that this is about five times faster than using a regular expression.
快速性能测试表明,这比使用正则表达式快五倍。
回答by Sgedda
As a string extension:
作为字符串扩展:
public static string RemoveIntegers(this string input)
{
return Regex.Replace(input, @"[\d-]", string.Empty);
}
Usage:
用法:
"My text 1232".RemoveIntegers(); // RETURNS "My text "
回答by Vitaly Yakel
the best design is:
最好的设计是:
public static string RemoveIntegers(this string input)
{
return Regex.Replace(input, @"[\d-]", string.Empty);
}
回答by Ali Rasoulian
Blow codes could help you...
吹码可以帮助你...
Fetch Numbers:
取号:
return string.Concat(input.Where(char.IsNumber));
Fetch Letters:
取信件:
return string.Concat(input.Where(char.IsLetter));