Regex for validating date in dd-Mmm-yyyy format

[亡魂溺海] 提交于 2021-02-05 09:33:11

问题


I have an text input box which needs to be validated. The user should be only able to enter the date in dd-Mmm-yyyy format. ex: 01-Jun-2013, 31-Aug-2015 and so on. Or they should be able to enter T+1, T+2,...T+99.

What kind of a regex pattern I could use to validate both of these. I think for validating the dd-Mmnm-yyyy, the following regex works:

^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4}$

Please help me with this!

Update: I just need the regex pattern for a single letter T followed by "+" and a number ranging from "1 to 99". i.e., [T+1... T+99]. The user should be only able to enter these numbers into the text field.


回答1:


T followed by "+" and a number ranging from "1 to 99"

Try with: T\+?\d{0,2} where:

  1. T literal "T";
  2. \+? - zero or one plus sign "+" with escape backslash (or other escape character, depends on language) - without it it will be treated as metacharacter '+'; the additional '?' sing means, that character before that could appear, but it is not necessary
  3. \d{0,2} - from zero to two digits;

DEMO




回答2:


Not sure what you mean by T+1, etc, but here's the bare minimum that does what you need:

^[01][0-9]-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$

You can also use the i flag to make the whole thing case insensitive.

http://www.regexr.com/3bdeu




回答3:


If I correctly understand your question, I added the possibility to enter someting matching (T\+[0-9]+) to your original regex.

^((([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-\d{4})|(T\+[0-9]+)$


来源:https://stackoverflow.com/questions/31463243/regex-for-validating-date-in-dd-mmm-yyyy-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!