Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c# - 正则表达式,仅接受数字(0-9)和无字符[重复](Regex that accepts only numbers (0-9) and NO characters [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

I need a regex that will accept only digits from 0-9 and nothing else.

(我需要一个正则表达式,它将只接受0-9之间的数字,而不能接受其他任何东西。)

No letters, no characters.

(没有字母,没有字符。)

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.

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

  ask by mo alaz translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A".

(您的正则表达式^[0-9]匹配以数字开头的任何内容,包括“ 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 * .

(要只接受一位数字,只需删除* 。)

UPDATE: You mixed up the arguments to IsMatch .

(更新:您混合了IsMatch的参数。)

The pattern should be the second argument, not the first:

(模式应该是第二个参数,而不是第一个:)

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

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

(注意:在JavaScript中, \d等效于[0-9] ,但在.NET中, \d默认情况下匹配任何Unicode十进制数字 ,包括诸如?(缅甸2)和?(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] (或提供RegexOptions.ECMAScript标志)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...