C# 整数大于 0 且小于 11 的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13508346/
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 08:48:32  来源:igfitidea点击:

Regular Expression for Integer greater than 0 and less than 11

c#regex

提问by Asynchronous

I am trying to modify this Regex so that you get numbers greater or equals 1 or less than or equals to 10. This Regex allows >= 0 or <= 10.

我正在尝试修改此正则表达式,以便您获得大于或等于 1 或小于或等于 10 的数字。此正则表达式允许 >= 0 或 <= 10。

I have a text field on a form that takes numbers equals or greater than 0 and less than 11. I could use IF's and logical operators, TryParse but I kinda like the Regex.

我在表单上有一个文本字段,它的数字等于或大于 0 且小于 11。我可以使用 IF 和逻辑运算符 TryParse,但我有点喜欢 Regex。

@"^\d$|^[1][0]$"

采纳答案by stema

You need to modify your regex only a little bit

你只需要稍微修改你的正则表达式

@"^[1-9]$|^10$"

You don't need the square brackets around single characters and I would use a group around the alternation and change it to

您不需要单个字符周围的方括号,我会在交替周围使用一组并将其更改为

@"^([1-9]|10)$"

See it here on Regexr

在 Regexr 上看到它

回答by Yes Barry

The answer is this is not something for which you should use regex. If anything you would use regular expressions to parse out the numbers and then compare them with standard if (num >= 0)etc.

答案是这不是您应该使用正则表达式的东西。如果有的话,您将使用正则表达式来解析数字,然后将它们与标准if (num >= 0)等进行比较。

// EDIT: replaced regex with this:
int number;
if (Int32.TryParse(myString, out number)) {
    // do something, like:
    if (number >= 0 || number <= 10) {

    }
}

回答by Kieren Johnstone

Here you are:

这个给你:

^(1|2|3|4|5|6|7|8|9|10)$

Very explicit, can't misinterpret, clear as day. Makes for a better regex for me. Short and cryptic isn't necessary here

非常明确,不能误解,清晰如天。为我提供更好的正则表达式。这里不需要简短和神秘

回答by FThompson

While I recommend simply using logical operators to check if an int is between 1 and 10, here's a working regex:

虽然我建议简单地使用逻辑运算符来检查 int 是否介于 1 和 10 之间,但这是一个有效的正则表达式:

^(10|[1-9])$

回答by Kapil Khandelwal

you can try this:

你可以试试这个:

^([1-9]|10)$

回答by Sergey Berezovskiy

If you are using WinForms, then NumericUpDowncontrol with MinValueequal to 1and MaxValueequal to 10 will do the job. Also you don't need parsing - property Valuewill contain your value (well, it will be of type decimal- just cast it to int).

如果您使用的是 WinForms,则等于和等于 10 的NumericUpDown控件将完成这项工作。此外,您不需要解析 - 属性将包含您的值(好吧,它将是类型- 只需将其强制转换为)。MinValue1MaxValueValuedecimalint

Another reason for using NumericUpDown- it does not allow to input anything except digits, and up-down arrows are saying to user - this control is waiting numbers from you.

使用的另一个原因NumericUpDown- 它不允许输入除数字以外的任何内容,并且向上向下箭头告诉用户 - 此控件正在等待您的数字。

回答by F11

Use Regex to check number from 1 to 10 -

使用正则表达式检查从 1 到 10 的数字 -

^([1-9]|10)$

^([1-9]|10)$