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]$"
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.
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).
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.
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
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
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) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With