【发布时间】:2010-06-17 14:48:23
【问题描述】:
我想去掉字符串中所有非数字的字母。最好是用正则表达式或其他东西制作的解决方案。在 C# 中。 怎么做?
【问题讨论】:
我想去掉字符串中所有非数字的字母。最好是用正则表达式或其他东西制作的解决方案。在 C# 中。 怎么做?
【问题讨论】:
使用正则表达式:
str = Regex.Replace(str, @"\D+", "");
\D 是 \d 的补码 - 匹配所有不是数字的内容。 + 将匹配其中的一个或多个(通常比一个一个好一点)。
使用 Linq(在 .Net 4.0 上):
str = String.Concat(str.Where(Char.IsDigit));
【讨论】:
string str = "ab123123abc"
str = Regex.Replace(str, @"[\w]", "");
【讨论】:
[\w] 是多余的,你不需要字符类。 \w 完全一样。但是,\w 包含字母和数字(以及下划线),因此最终会出现特殊字符和空格。
我更喜欢使用 not ^ like ^\d or ^[0-9]
string resultString = null;
try {
resultString = Regex.Replace(subjectString, @"[^\d]+", "");
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
【讨论】:
try/catch 块,唯一可能的例外是subjectString 是null,您最好检查一下。对于此模式,您不会得到 ArgumentException - 这是正确的 :) 但是,应该是“[^\d] 或 [^0-9]”
string result = System.Text.RegularExpressions.Regex.Replace("text to look for stuff", "pattern", "what to replace it with")
【讨论】: