【发布时间】:2010-12-06 07:25:21
【问题描述】:
假设我有一个包含数字和其他字符的字符串。
我只想将字符串简化为数字。
F.e.从 23232-2222-d23231 到 23232222223231
这可以用 string.replace() 来完成吗?
如果没有,最简单最短的方法是什么?
10 倍!
【问题讨论】:
假设我有一个包含数字和其他字符的字符串。
我只想将字符串简化为数字。
F.e.从 23232-2222-d23231 到 23232222223231
这可以用 string.replace() 来完成吗?
如果没有,最简单最短的方法是什么?
10 倍!
【问题讨论】:
你可以使用 LINQ:
string allDigits = new String(input.Where(c => Char.IsDigit(c)).ToArray());
【讨论】:
是的,您可以使用 String.replace,但使用正则表达式会更明智,这样您就可以更轻松地匹配更多条件。
【讨论】:
有很多可能性,从正则表达式到自己处理文本。我会这样做:
Regex.Replace(input, @"\D+", "")
【讨论】:
试试
string str="23232-2222-d23231";
str=Regex.Replace(str, @"\D+", String.Empty);
【讨论】:
好吧,你会得到大约 874355876234857 个使用 String.Replace 和 Regex.Replace 的答案,所以这里有一个 LINQ 解决方案:
code = new String((from c in code where Char.IsDigit(c) select c).ToArray());
或者使用扩展方法:
code = new String(code.Where(c => Char.IsDigit(c)).ToArray());
【讨论】:
Regex 对象,使用静态Replace 方法,还是重新创建了几十个Regex 对象?第一个选项将是最快的,但可能不代表现实世界的使用。
采样的正则表达式是最简单和最短的。
不知道下面会不会更快?
string sample = "23232-2222-d23231";
StringBuilder resultBuilder = new StringBuilder(sample.Length);
char c;
for (int i = 0; i < sample.Length; i++)
{
c = sample[i];
if (c >= '0' && c <= '9')
{
resultBuilder.Append(c);
}
}
Console.WriteLine(resultBuilder.ToString());
Console.ReadLine();
猜测这取决于一些事情,包括字符串长度。
【讨论】:
您可以使用简单的扩展方法:
public static string OnlyDigits(this string s)
{
if (s == null)
throw new ArgumentNullException("null string");
StringBuilder sb = new StringBuilder(s.Length);
foreach (var c in s)
{
if (char.IsDigit(c))
sb.Append(c);
}
return sb.ToString();
}
【讨论】:
您可以使用正则表达式。
string str = "sdfsdf99393sdfsd";
str = Regex.Replace(str, @"[a-zA-Z _\-]", "");
我以前用它只返回字符串中的数字。
【讨论】:
string str = "foo/234335"?哎呀。
我会使用正则表达式。
看到这个帖子Regex for numbers only
【讨论】:
string.Replace() 不可能(很容易)。最简单的解决方案是以下函数/代码:
public string GetDigits(string input)
{
Regex r = new Regex("[^0-9]+");
return r.Replace(input, "");
}
【讨论】:
最好的方法是使用正则表达式。你的例子是:
RegEx.Replace("23232-2222-d23231", "\\D+", "");
【讨论】:
+或不使用量词。使用 * 会导致大量 0 长度匹配。
最简单的方法是使用替换。
string test = "23232-2222-d23231";
string newString = test.Replace("-","").Replace("d","");
但使用 REGEX 会更好,但更难。
【讨论】: