Reputation: 2415
I have been searching high and low for a regex to use on a text box in ASP.Net to validate a four digit number.
The four digit number is split into two, the first digit needs to be 0 - 9, and the last part of the number can be 001 to 365. So, you could 1001, or 0365, which will be valid numbers. Basically, what it is a code for dates, the first part of the number or first digit is the year, and the last part is the day/month, so 001 is 1st Jan or 365 is 31st December.
Can anyone help?
Upvotes: 0
Views: 1996
Reputation: 50220
I agree with @greg, this is not an appropriate use for regexps. But since the number of digits is fixed, it's really not hard to do:
^\d([12]\d\d|3[0-5]\d|36[0-5]|0\d[1-9]|0[1-9]\d)$
No conversion to int for verification is needed.
Translation: The first digit can be anything; it must be followed by any 3-digit number that: starts with 1 or 2; or starts with 3[0-5]; or starts with 36 and is up to 365; or starts with 0 and has one non-zero digit (thanks @m.buettner!)
Note: In the above, \d
means "digit". On .NET, you can substitute [0-9]
for each \d
.
Bonus: To allow 366 days on leap years, just double the above and condition it on the first digit. If 2 means 2012 and 0 means 2020, the leap year digits are 2,6,0, and you have:
^([1345789]([12]\d\d|3[0-5]\d|36[0-5]|0\d[1-9]|0[1-9]\d)|[260]([12]\d\d|3[0-5]\d|36[0-6]|0\d[1-9]|0[1-9]\d))$
Yeah, it's getting out of hand. If you can convert to int and check that, do so.
Upvotes: 2
Reputation: 44289
Validating number ranges with regex is a bit tricky but possible:
^[0-9](00[1-9]|0[1-9][0-9]|[12][0-9][0-9]|3[0-5][0-9]|36[0-5])$
What I recommend you do instead, is this:
^[0-9]([0-9]{3})$
Then you take the first captured match (which will contain the last three digits only) and check whether it is greater than 0
and less than 366
:
Match m = Regex.Match(input, @"^\d(\d{3})$");
int day = int.Parse(m.Groups[1].Value);
if(day > 0 && day < 366)
// valid
else
// invalid
Upvotes: 3
Reputation: 2758
I agree with Greg. You can verify that the entry is numeric and basically conforms to your specs, but you still need to check programmatically after validating the format.
One regex for this would be /^[0-9]{1}[0-3]{1}[0-9]{2}$/
Then you'll have to split off the last three digits and verify.
www.regextester.com is nice for trying out expressions quickly. www.regexlib.com is a good repository of lots of user-submitted regex strings.
Upvotes: 1