C# 仅接受数字 (0-9) 和 NO 字符的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19715303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:42:23  来源:igfitidea点击:

Regex that accepts only numbers (0-9) and NO characters

c#regex

提问by mo alaz

I need a regex that will accept only digits from 0-9 and nothing else. No letters, no characters.

我需要一个只接受 0-9 数字而不接受其他数字的正则表达式。没有字母,没有字符。

I thought this would work:

我认为这会奏效:

^[0-9]

or even

甚至

\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.

我认为上面的两个正则表达式都可以解决问题,但我不确定为什么它接受这些字符。

EDIT:

编辑:

This is exactly what I am doing:

这正是我正在做的:

 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.

这允许我上面提到的字符。

采纳答案by Michael Liu

Your regex ^[0-9]matches anything beginningwith a digit, including strings like "1A". To avoid a partial match, append a $to the end:

您的正则表达式^[0-9]匹配以数字开头的任何内容,包括像“1A”这样的字符串。为避免部分匹配,请$在末尾附加 a :

^[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 *.

这接受任意数量的数字,包括无。要接受一位或多位数字,请将 更改*+。要只接受一位数字,只需删除*.

UPDATE:You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

更新:您混淆了IsMatch. 模式应该是第二个参数,而不是第一个:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION:In JavaScript, \dis equivalent to [0-9], but in .NET, \dby 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.ECMAScriptflag).

注意:在 JavaScript 中,\d相当于[0-9],但在 .NET 中,\d默认情况下匹配任何Unicode 十进制数字,包括异国情调的票价,如 ? (缅甸 2) 和 ? (N'Ko 9)。除非您的应用准备处理这些字符,否则请坚持使用[0-9](或提供RegexOptions.ECMAScript标志)。