Regular Expression for Integer greater than 0 and less than 11 - c#

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]$"

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 are using WinForms, then NumericUpDown control with MinValue equal to 1 and MaxValue equal to 10 will do the job. Also you don't need parsing - property Value will contain your value (well, it will be of type decimal - just cast it to int).
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.

While I recommend simply using logical operators to check if an int is between 1 and 10, here's a working regex:
^(10|[1-9])$

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

you can try this:
^([1-9]|10)$

Use Regex to check number from 1 to 10 -
^([1-9]|10)$

Related

Regex c# only positive numbers

I am looking for a regular expression that validates only positive numbers(integers):
0-999 and first number not 0.
My example not work:
string pattern = #"^\d+$";
How decided positive numbers pattern?
You could force the first digit to be 1-9, and then have any or no digits follow it, like so;
string pattern = #"^[1-9]\d*$";
You can also restrict the amount of digits by putting a numbered constraint on it.
string pattern = #"^[1-9]\d{0,2}$";
The top one will accept any positive integer >0, while the bottom one will accept only 1-999.
How about
#"^[1-9]\d?\d?$"
1-9 followed by 2 optional digits?
use this regular expression ^[1-9]\d{0,2}$
If you just want to validate an input, why not using TryParse?
Regular Expression for positive numbers in C#
double result = 0;
if (Double.TryParse(myString, out result))
{
// Your conditions
if (result > 0 && result < 1000)
{
// Your number
}
}
You can use a lot of useful regex tools online like http://gskinner.com/RegExr/
there's a lot of ready to use examples from which you can start to get your own!
The positive number with two digits after comma:
\d*\,\d\d

Regular expression for 10 digit number without any special characters

What is the regular expression for a 10 digit numeric number (no special characters and no decimal).
Use this regular expression to match ten digits only:
#"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
#"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:
#"(?<!\d)\d{10}(?!\d)"
Use the following pattern.
^\d{10}$
This works for me:
only 10 digit number is accepted.
^[0-9]{10}$
\d{10}
I believe that should do it
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(#"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
Use this:
\d{10}
I hope it helps.

c# regular expression to only allow numbers between 1 and n

I will admit i know nothing about regular expressions. what I am trying to do is use a variable as part of a regular expression. I want a validation to occur on each character input, which it does, and only allow character between 1 and n, n can be any number from 1 to 999, how do I do that? 1, 2, 3, 15, 23, 500 are all valid whereas 003, 0, 3t3 are all invalid.
thanks, R.
I would suggest the following instead, which is analogous to #Doug's answer:
Find a string that starts with 1-9, and is followed by zero, one, or two digits (0-9) and nothing more.
^[1-9][0-9]{0,2}$
This also has the nicety of scaling well if the requirements change, to say 1-9999. In which case, the regex simply becomes:
^[1-9][0-9]{0,3}$
This should do it: ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$
The trick is to think of the problem as a series of digits evaluated one at a time instead of one whole number.
Enjoy!
Are you sure that a regex is the best solution here?
You could use int.TryParse(string, out value)
if this succeeds then ensure that the resultant int is in range...

Regular expression where part of string must be number between 0-100

I need to validate serial numbers. For this we use regular expressions in C#, and a certain product, part of the serial number is the "seconds since midnight". There are 86400 seconds in a day, but how can I validate it as a 5-digit number in this string?:
654984051-86400-231324
I can't use this concept:
[0-8][0-6][0-4][0-0][0-0]
Because then 86399 wouldn't be valid. How can I overcome this? I want something like:
[00000-86400]
UPDATE
I want to make it clear that I'm aware of - and agree with - the "don't use regular expressions when there's a simpler way" school-of-thought. Jason's answer is exactly how I'd like to do it, however this serial number validation is for all serial numbers that pass through our system - there's currently no custom validation code for these specific ones. In this case I have a good reason for looking for a regex solution.
Of course, if there isn't one, then that makes the case for custom validation for these particular products undeniable, but I wanted to explore this avenue fully before going with a solution that requires code changes.
Don't use regex? If you're struggling to come up with the regex to parse this that says that maybe it's too complex and you should find something simpler. I see absolutely no benefit to using regex here when a simple
int value;
if(!Int32.TryParse(s, out value)) {
throw new ArgumentException();
}
if(value < 0 || value > 86400) {
throw new ArgumentOutOfRangeException();
}
will work just fine. It's just so clear and easily maintainable.
You don't want to try to use regular expressions for this, you'll end up with something incomprehensible, unwieldy, and difficult to modify (somebody will probably suggest one :). What you want to do is match the string using a regex to make sure that it contains digits in the format you want, then pull out a matching group and check the range using an arithmetic comparison. For example, in pseudocode:
match regex /(\d+)-(\d+)-(\d+)/
serial = capture group 2
if serial >= 0 and serial <= 86400 then
// serial is valid
end if
Generate a Regular Expression to Match an Arbitrary Numeric Range
http://utilitymill.com/utility/Regex_For_Range
yields the following regex expression:
\b0*([0-9]{1,4}|[1-7][0-9]{4}|8[0-5][0-9]{3}|86[0-3][0-9]{2}|86400)\b
Description of output:
First, break into equal length ranges:
0 - 9
10 - 99
100 - 999
1000 - 9999
10000 - 86400
Second, break into ranges that yield simple regexes:
0 - 9
10 - 99
100 - 999
1000 - 9999
10000 - 79999
80000 - 85999
86000 - 86399
86400 - 86400
Turn each range into a regex:
[0-9]
[1-9][0-9]
[1-9][0-9]{2}
[1-9][0-9]{3}
[1-7][0-9]{4}
8[0-5][0-9]{3}
86[0-3][0-9]{2}
86400
Collapse adjacent powers of 10:
[0-9]{1,4}
[1-7][0-9]{4}
8[0-5][0-9]{3}
86[0-3][0-9]{2}
86400
Combining the regexes above yields:
0*([0-9]{1,4}|[1-7][0-9]{4}|8[0-5][0-9]{3}|86[0-3][0-9]{2}|86400)
Tested here:
http://osteele.com/tools/rework/
With the standard 'this-is-not-a-particularly-regexy-problem' caveat,
[0-7]\d{4}|8[0-5]\d{3}|86[0-3]\d{2}|86400
If you really need a pure regex solution I believe this would work although the other posters make a good point about only validating they are digits and then using a matching group to validate the actual number.
([0-7][0-9]{4}) | (8[0-5][0-9]{3}) | (86[0-3][0-9]{2}) | (86400)
I would use regex combined with some .NET code to accomplish this. A pure regex solution isn't going to be easy or efficient to handle large number ranges.
But this will:
Regex myRegex = new Regex(#"\d{9}-(\d{5})-\d{6}");
String value = myRegex.Replace(#"654984051-86400-231324", "$1");
This will grab the value 86400 in this case. And then you'd just check if the captured number is between 0 and 86400 as per Jason's answer.
I don't believe this is possible in regular expressions since this isn't something that can be checked as part of a regular language. In other words, a finite state automata machine cannot recognize this string so a regular expression cannot either.
Edit: This can be recognized by a regex, but not in an elegant way. It would require a monster or chain (e.g.: 00000|00001|00002 or 0{1,5}|0{1,4}1|0{1,4}2). To me, having to enumerate such a large set of possibilities makes it clear that while it is technically possible, it is not feasible or manageable.

how to write this regular expression?

an 20 - 24 char long alphanumeric string with no spaces and no symbols that has at least 2 digits
AAAAAAAAAAAAAAAAAAAA - not valid
AAAAAA0AAAAAAAAA0AAA - valid
AAAAAA01AAAAAAAAA0AAA - valid
AAAAAA0AAAAAAAAA0AAA# - not valid
I think this is only possible with look-ahead assertion:
^(?=[a-zA-Z\d]{20,24}$)[a-zA-Z]*\d[a-zA-Z]*\d[a-zA-Z\d]*$
The look-ahead assertion ((?=[a-zA-Z\d]{20,24}$)) checks if the string has the expected form (20–24 alphanumeric characters). And the second part ([a-zA-Z]*\d[a-zA-Z]*\d[a-zA-Z\d]*) checks if it contains at least two digits.
I think that this is the simplest pattern: First make a positive lookahead to check that there are at least two digits, then match 20-24 alphanumeric characters:
^(?=.*\d.*\d)[A-Za-z\d]{20,24}$
I'm going to be abstract because this sounds like homework (if it is, please tag it as such).
You can restrict the number of times a pattern matches with {min,max}
You can restrict which characters match with [charlist]
You can impose additional restrictions with what's called zero-width positive lookahead (there's also a negative form). The syntax varies, so check the docs for your environment.
Update your question (& tags) if you need more help.
Gumbo has a correct expression for the requirements.
It could be shortened, but his was more clear and probably faster than the short version.
var rX=/^(?=[a-zA-Z\d]{20,24}$)([a-zA-Z]*\d){2,}/
in JS (not confident enough with C# syntax):
if (str.length >= 20 && str.length <= 24 && /([a-z]*[0-9]){2}[a-z0-9]*/i.test(str)) {
// match found
}
Basically the same idea as Gumbo just a little shorter:
^(?=[\w\d]{20,24}$)[\w]*\d[\w]*\d[\w\d]*$

Categories