I need a regex to validate:
- just numbers
- it have to start with the number 20
- the five number needs to be 0 or 1
- the seven number needs to be 1, 2 or 3
@"^20\d{2}[0-1]\d[1-3]$"
Starts with 20, then 2 of any digits, then 0 or 1, then any digits, then 1, 2 or 3. If you need additional digits after the 7th, you can insert a \d*
before the $
:
@"^20\d{2}[0-1]\d[1-3]\d*$"
Edit: As CodeMonkey points out, \d
will be interpreted in C# as an escape sequence, so be sure to use a verbatim string (as now shown above.)
Are you going to validate a date YYYYMMDD
?
Try this: http://programmerramblings.blogspot.com/2008/08/elegant-date-validation-in-c.html
Or this: http://www.c-sharpcorner.com/UploadFile/scottlysle/DateValCS02222009225005PM/DateValCS.aspx
Or this: http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
The regex:
^20\d\d[01]\d[123]\d*$
Starts with 20, then 2 of any digits, then 0 or 1, then any digits, then 1, 2 or 3, then only digits or nothing.
20\d{2}[01]\d{1}[123]
Probably not very optimized, but it works :)
20\d{2}(0|1)\d[1-3]
I think this will work
Since you are using C# I would recommend using the regular expression tester here http://regexhero.net/tester/ It is great, you will be able to see the results of you expression highlighted as you build your expression.
I would go with
^20\d{2}[01]\d[1-3]\d*$
精彩评论