C# 如何使用正则表达式从数值中删除字符

C# 如何使用正则表达式从数值中删除字符,c#,regex,C#,Regex,我的值是4,59999/-。我的代码是 if (Regex.IsMatch(s,@"\b[1-9]\d*(?:,[0-9]+)*/?-?")) { string value = Regex.Replace(s, @"[^\d]", " "); textBox2.Text= value; } 输出是:4559999,我需要它是459999(不带“,”,“/”,“-”和“”)。用空字符串替换即可 string value = Regex.Replace(s, @"[^\d]",

我的值是4,59999/-。我的代码是

if (Regex.IsMatch(s,@"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
    string value = Regex.Replace(s, @"[^\d]", " ");
    textBox2.Text= value;
} 

输出是:4559999,我需要它是459999(不带“,”,“/”,“-”和“”)。

用空字符串替换即可

string value = Regex.Replace(s, @"[^\d]", ""); // See the change in the replace string.
textBox2.Text= value;
注意您不需要使用
if
,因为只有在非数字(
[^\d]
)匹配时,正则表达式替换才会起作用。

您正在用空格替换“、”、“/”、“-”和“”。请尝试以下方法:

string value = Regex.Replace(s, @"[^\d]", "");

希望这能有所帮助。

是否应该用空字符串代替空格


Regex.Replace(s,@“[^\d]”,String.Empty)

当前您正在用空格替换这些字符。改为使用一组空引号

if (Regex.IsMatch(s,@"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
    string value = Regex.Replace(s, @"[^\d]", "");
    textBox2.Text= value;
} 

没有正则表达式怎么样

var s = "4,59,999/-";
var array = s.Where(c => char.IsDigit(c)).ToArray(); 
或更短

var array = s.Where(char.IsDigit).ToArray(); 

您可以在中使用此数组


您不需要正则表达式,可以使用:

 textBox2.Text = String.Concat(s.Where(Char.IsDigit));
更好的方法是使用
decimal.Parse
/
TryParse

string s = "4,59,999/-.";
decimal price;
if (decimal.TryParse(s.Split('/')[0], NumberStyles.Currency, NumberFormatInfo.InvariantInfo, out price))
    textBox2.Text = price.ToString("G");

Linq是一种可能的解决方案:

  String s = "4,59,999/-";
  ...
  textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());
String s=“4,59999/-”;
...

textBox2.Text=newstring(s.Where(item=>item>='0'&&item尝试类似的方法在php中100%工作,所以只需更改一些C的语法即可#



不是空白。它是空字符串。@phoog是的,但我试图解释OP-dix错了什么,而不是他应该做什么,我明白了。我稍微编辑了一下你的答案,让它更清楚。我怀疑有设计缺陷。为什么这个值首先是字符串?
  String s = "4,59,999/-";
  ...
  textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());
<?php
    $str = "4,59,999/-.";
    echo $str = preg_replace('/[^a-z0-9]/', '', $str);
?>