正则表达式的数字只 [英] Regex for numbers only
问题描述
我没有使用常规的前pressions可言,所以我有困难的故障排除。我要匹配的正则表达式,只有当所包含的字符串是所有的数字;但它下面的两个例子是匹配包含字符串的所有数字加一个等号,如1234 = 4321。我敢肯定有一种方法来改变这种行为,但正如我所说,我从来没有真正做了很多与常规的前pressions。
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". 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
}
在它的事项,我使用C#和.NET2.0案例
In case it matters, I'm using C# and .NET2.0.
推荐答案
使用的开始和结束锚。
Regex regex = new Regex(@"^\d$");
使用^ \\ D + $
如果你需要匹配多个数字。
Use "^\d+$"
if you need to match more than one digit.
注意\\ D
将匹配 [0-9]
和其他数字字符,如东方阿拉伯语数字 0123456789
。使用^ [0-9] + $
来限制比赛只是阿拉伯数字0 - 9
Note that "\d"
will match [0-9]
and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩
. Use "^[0-9]+$"
to restrict matches to just the Arabic numerals 0 - 9.
如果你需要包括任何数字再$ P $不仅仅是个数字(如对于初学者十进制值)等psentations,然后看看 @ tchrist 的 COM prehensive指导与常规的前pressions 的分析数字。
If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.
这篇关于正则表达式的数字只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!