我根本没用过正则表达式,所以在故障排除方面遇到了困难。我想正则表达式匹配仅当包含的字符串是所有数字;但是在下面两个例子中,它匹配的是一个包含所有数字加上等号的字符串,比如“1234=4321”。我确信有一种方法可以改变这种行为,但正如我所说的,我从来没有真正使用过正则表达式。

string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");

if (regex.IsMatch(compare))
{ 
    //true
}

regex = new Regex("[0-9]");

if (regex.IsMatch(compare))
{ 
    //true
}

以防万一,我使用的是c#和。net 2.0。


当前回答

也许我的方法对你有帮助。

    public static bool IsNumber(string s)
    {
        return s.All(char.IsDigit);
    }

其他回答

对不起,格式很难看。 对于任意位数:

[0-9]*

对于一个或多个数字:

[0-9]+

也许我的方法对你有帮助。

    public static bool IsNumber(string s)
    {
        return s.All(char.IsDigit);
    }

这适用于整数和十进制数。如果数字有昏迷千分隔符,它就不匹配,

"^-?\\d*(\\.\\d+)?$"

与此匹配的字符串:

894
923.21
76876876
.32
-894
-923.21
-76876876
-.32

一些字符串没有:

hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.

检查字符串是否为uint, ulong或只包含数字1 .(点)和数字 样例输入

Regex rx = new Regex(@"^([1-9]\d*(\.)\d*|0?(\.)\d*[1-9]\d*|[1-9]\d*)$");
string text = "12.0";
var result = rx.IsMatch(text);
Console.WriteLine(result);

样品

123 => True
123.1 => True
0.123 => True
.123 => True
0.2 => True
3452.434.43=> False
2342f43.34 => False
svasad.324 => False
3215.afa => False

我认为这个是最简单的,它接受欧洲和美国的数字书写方式,例如美国10,555.12欧洲10.555,12 此外,这个语句不允许几个逗号或点一个接一个,例如10..22或10。22 除了。55这样的数字,55可以通过。这可能很方便。

^([,|.]?[0-9])+$