本文翻译自:Regex for numbers only
I haven't used regular expressions at all, so I'm having difficulty troubleshooting. 我根本没有使用过正则表达式,因此我很难进行故障排除。 I want the regex to match only when the contained string is all numbers; 我希望正则表达式仅在包含的字符串为全数字时才匹配; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". 但是在下面的两个示例中,它匹配包含所有数字和等号(例如“ 1234 = 4321”)的字符串。 I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions. 我敢肯定有一种方法可以改变这种行为,但是正如我所说,我从未真正对正则表达式做过很多事情。
string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");
if (regex.IsMatch(compare))
{
//true
}
regex = new Regex("[0-9]");
if (regex.IsMatch(compare))
{
//true
}
In case it matters, I'm using C# and .NET2.0. 万一重要,我使用的是C#和.NET2.0。
参考:https://stackoom.com/question/193v/正则表达式仅用于数字
Another way: If you like to match international numbers such as Persian or Arabic, so you can use following expression: 另一种方式:如果您想匹配波斯或阿拉伯等国际号码,则可以使用以下表达式:
Regex = new Regex(@"^[\p{N}]+$");
To match literal period character use: 要匹配文字字符,请使用:
Regex = new Regex(@"^[\p{N}\.]+$");
Perhaps my method will help you. 也许我的方法会对您有所帮助。
public static bool IsNumber(string s)
{
return s.All(char.IsDigit);
}
This works with integers and decimal numbers. 这适用于整数和十进制数。 It doesn't match if the number has the coma thousand separator , 如果数字带有逗号分隔符,则不匹配,
"^-?\\d*(\\.\\d+)?$"
some strings that matches with this: 与此匹配的一些字符串:
894
923.21
76876876
.32
-894
-923.21
-76876876
-.32
some strings that doesn't: 一些没有的字符串:
hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.
Sorry for ugly formatting. 抱歉,格式不正确。 For any number of digits: 对于任何数字:
[0-9]*
For one or more digit: 对于一位或多位数字:
[0-9]+
If you need to check if all the digits are number (0-9) or not, 如果您需要检查所有数字是否都是数字(0-9),
^[0-9]+$
1425 TRUE 1425是
0142 TRUE 0142是
0 TRUE 0是
1 TRUE 1是
154a25 FALSE 154a25错误
1234=3254 FALSE 1234 = 3254假