开发者

Need help creating a Regex [closed]

开发者 https://www.devze.com 2023-03-29 03:58 出处:网络
It's difficult to tell what is being asked here. This ques开发者_StackOverflow中文版tion is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its cu
It's difficult to tell what is being asked here. This ques开发者_StackOverflow中文版tion is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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*$
0

精彩评论

暂无评论...
验证码 换一张
取 消