Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for Integer greater than 0 and less than 11

Tags:

c#

regex

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.

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.

@"^\d$|^[1][0]$"
like image 508
Asynchronous Avatar asked Nov 22 '12 08:11

Asynchronous


People also ask

What is regular expression for integer?

1.5 Example: Positive Integer Literals [1-9][0-9]*|0 or [1-9]\d*|0. [1-9] matches any character between 1 to 9; [0-9]* matches zero or more digits. The * is an occurrence indicator representing zero or more occurrences. Together, [1-9][0-9]* matches any numbers without a leading zero.

How do you specify a number range in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"


2 Answers

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

like image 139
stema Avatar answered Oct 30 '22 08:10

stema


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.

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

    }
}
like image 44
Yes Barry Avatar answered Oct 30 '22 08:10

Yes Barry