正则表达式只接受数字(0-9),并没有字符 [英] Regex that accepts only numbers (0-9) and NO characters
问题描述
我需要一个正则表达式,将只接受数字从0到9,没有别的。人无信,无字符。
I need a regex that will accept only digits from 0-9 and nothing else. No letters, no characters.
我认为这将工作:
^[0-9]
甚至
\d+
但这些接受字符:^,$,(,)等
but these are accepting the characters : ^,$,(,), etc
我想,无论是上述正则表达式会做的伎俩,我不知道为什么它接受这些字符。
I thought that both the regexes above would do the trick and I'm not sure why its accepting those characters.
编辑:
这正是我在做什么:
private void OnTextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch("^[0-9]", textbox.Text))
{
textbox.Text = string.Empty;
}
}
这是允许我在上面提到的人物。
This is allowing the characters I mentioned above.
推荐答案
您正则表达式 ^ [0-9]
匹配任何的开始的有数字,包括像1A字符串。为了避免部分匹配,追加 $
来结束:
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
此接受任何数量的数字,包括无。要接受一个或多个数字,更改 *
到 +
。要接受恰好有一个数字,只是删除 *
。
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
更新:您混合起来的参数 IsMatch
。该模式应该是第二个参数,不是第一:
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
注意:在JavaScript中, \\ D
等同于 [0-9]
,但在.NET中, \\ D
默认匹配任何统一$ C $ç十进制数字,包括异国风味如2(缅甸2)和߉(西非书面文9)。除非你的应用程序是ppared处理这些字符$ P $,坚持使用 [0-9]
(或提供<一个href=\"https://msdn.microsoft.com/en-us/library/yd1hzczs(v=vs.110).aspx#Anchor_10\">RegexOptions.ECMAScript标志)。
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ႒ (Myanmar 2) and ߉ (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
这篇关于正则表达式只接受数字(0-9),并没有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!