c#检查文本框中的整数

时间:2014-04-14 11:01:36

标签: c# regex string textbox int

我正在尝试检查文本框是否包含数字。问题是它总是返回它包含一个非数字字符。 我尝试了几种方法,但似乎都没有。

我尝试过的方法之一是:

if( Regex.IsMatch(tb.Text.Trim(), @"^[0-9]+$")) // tb.Text is the textbox 

我在文本框中输入的内容无关紧要,它总是返回它包含非数字字符(我尝试输入1-9,'a','b')

4 个答案:

答案 0 :(得分:4)

您可以将字符串解析为特定的数字类型,即

double result;
if (!double.TryParse(tb.Text, out result))
{
  //text is not a valid double;
  throw new Exception("not a valid number");
}
//else the value is within the result variable

您的正则表达式似乎只需要整数值,因此您应该使用int.TryParselong.TryParse代替。


快速而肮脏的测试程序:

void Main()
{
    TestParse("1");
    TestParse("a");
    TestParse("1234");
    TestParse("1a");
}

void TestParse(string text)
{
  int result;
  if (int.TryParse(text, out result))
  {
    Console.WriteLine(text + " is a number");
  }
  else
  {
    Console.WriteLine(text + " is not a number");
  }
}

结果:

1 is a number 
a is not a number  
1234 is a number  
1a is not a number

答案 1 :(得分:2)

您可以替换Regex

if(Regex.IsMatch(tb.Text.Trim(), @"[0-9]"))

或者为此:

if(Regex.IsMatch(tb.Text.Trim(), @"\d"))

答案 2 :(得分:1)

你可以使用TryParse:

int value;

bool IsNumber = int.TryParse(tb.Text.Trim(), out value);

if(IsNumber)
{
    //its number
}

答案 3 :(得分:0)

private void btnMove_Click(object sender, EventArgs e)
        {
            string check = txtCheck.Text;
            string status = "";
            for (int i = 0; i < check.Length; i++)
            {
                if (IsNumber(check[i]))
                status+="The char at "+i+" is a number\n";
            }
            MessageBox.Show(status);
        }
        private bool IsNumber(char c)
        {
            return Char.IsNumber(c);
        }
相关问题