正则表达式仅允许 100 到 999999 之间的数字
任何人都可以帮助使用正则表达式的 C# 代码来验证仅接受 100 到 999999 之间数字的文本框
谢谢, 吕.
Can anyone help with C# code using regular expressions to validate a textbox which accepts only numbers between 100 and 999999
Thanks,
Lui.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您不需要为此使用正则表达式。
编辑:如果 CF 是目标,则不能使用
int.TryParse()
。回退到int.Parse()
并输入一些更多的错误捕获代码:You don't need a regex for this.
EDIT: If the CF is targetted, then you can't use
int.TryParse()
. Fallback onint.Parse()
instead and type a little more error-catching code:您的要求转换为三到六位数字,首先不是零。我不记得 C# 默认情况下是否锚定 RE,所以我也将它们放入其中。
Your requirement translates to three to six digits, first not zero. I can't remember whether C# anchors REs by default, so I've put them in too.
一种简单的方法是使用正则表达式
如果您想允许前导零(但仍保持 6 位数字限制),则正则表达式将是
最后一个可能值得一些解释:它首先使用正向先行 [
(?= )
] 以确保整个输入为 3 到 6 位数字,然后确保它由任意数量的前导零后跟 100-999999 范围内的数字组成。但是,使用更适合该任务的东西可能是个好主意(也许是数字比较?)。
A straightforward approach would be to use the regex
If you want to allow leading zeroes (but still keep the 6-digit limit) the regex would be
This last one probably merits some explanation: it first uses positive lookahead [
(?=)
] to make sure that the whole input is 3 to 6 digits, and then it makes sure that it's made up of any number of leading zeroes followed by a number in the range 100-999999.However, it's possibly a good idea to use something more suited to the task (maybe a numeric comparison?).
这就能解决问题:
This will do the trick:
你必须使用正则表达式吗?怎么样
Do you have to use regex? How about
您可以考虑的另一种方法
[1-9]\d{2,5}
another approach you could consider
[1-9]\d{2,5}
为什么不使用 NumericUpDown 控件来代替您指定了最小值和最大值吗?
而且它也只允许数字,从而节省了额外的验证以确保可以输入任何非数字的内容
从示例中:
Why not use a NumericUpDown control instead which lets you specifiy a Minimum and Maximum value?
And it will only allow numbers too, saving you additional validation to ensure anything non-numeric can be entered
From the example:
也许接受前导零:
And maybe accepting leading zeros: