简体   繁体   English

这段时间正则表达式如何工作?

[英]How does this time Regex Work?

I've just inherited a projected with a lot of client side validation. 我刚刚继承了一个带有许多客户端验证的项目。

In this I have found a regex checker, as expected without a comment in sight. 在这里,我找到了一个正则表达式检查器,正如预期的那样,没有任何评论。 I'll admit regex is definitely one of my failing points. 我承认正则表达式绝对是我的失败之处之一。 (In Javascript!) (使用Javascript!)

var myRegxp = /(([0]*[1-9]{1})|([1]{1}[0-2]{1}))(\/{1})((19[0-9]{2})|([2-9]{1}[0-9]{3}))$/;
if (!myRegxp.test(args.Value))
{//do fail stuff here};

I'm pretty sure from the rest of the page that it's supposed to be checking for some sort of date format. 从页面的其余部分,我很确定应该检查某种日期格式。 Would this pass MM/YYYY. 这会通过MM / YYYY吗? From some early testing, it almost does it. 从一些早期测试来看,它几乎可以做到。

If this regex doesn't match MM/YYYY, what would be the best way to do this? 如果此正则表达式与MM / YYYY不匹配,什么是最好的方法?

Any advice from the regex masters would be appreciated. 来自正则表达式大师的任何建议将不胜感激。

It should end with MM/YYYY (where MM is 1-12 and YYYY is 1900-9999) 它应以MM / YYYY结尾(其中MM为1-12,而YYYY为1900-9999)

(matching month) (匹配月份)

([0]*[1-9]{1})
zero or more occurences of '0', and one occurence of 1-9
Example match: 01

OR 要么

([1]{1}[0-2]{1})
1 match of '1', 1 match of 0-2
Example match: 10

Second part (year), first it literally match '/' with: 第二部分(年份),首先将“ /”与以下内容进行字面匹配:

(\/{1})

Then the year: 然后年份:

((19[0-9]{2})
One match of '/', 19 and two matches of 0-9 (looks like a year in the range 1900-1999)
Example match: 1900

OR 要么

([2-9]{1}[0-9]{3})
1 match of 2-9 and thee matches of 0-9 (looks like a year in the range 2000-9999
Example match: 2000

A simplified RE: 简化的RE:

var myRegExp = /^(0[1-9]|1[0-2])\/(19\d{2}|[2-9]\d{3})$/;

Note: \\d is a character class for 0-9 . 注意: \\d0-9的字符类。 I've removed parentheses used for grouping because these are not used in myRegExp.test . 我删除了用于分组的括号,因为myRegExp.test中没有使用这些括号。 Replaced [0]* by 0? [0]*替换为 0? since it should not match 0000001/2010 , but it should match 1/2010 . 因为它不应该匹配 0000001/2010 ,但是应该匹配 1/2010 Replaced [0]* by 0 since it should literally match 01 and not 1 . [0]*替换为0因为它实际上应匹配01而不是1 The ^ and $ are anchors, causing it to match from begin to end. ^$是锚点,导致其从开始到结束都匹配。 When leaving these out, this RE would match any text containing MM/YYYY. 忽略这些内容时,此RE将匹配任何包含MM / YYYY的文本。

I would agree - it is checking dates in the format MM/yyyy . 我同意-它以MM / yyyy格式检查日期。

It allows any number of leading zeros on the month. 它允许每月任意数量的前导零。 It allows years matching 19 xx or anything else starting with a digit between 2 and 9 inclusive. 它允许年份匹配19 xx或其他任何以2929之间的数字开头的数字。 This means that it allows anything up to 9999 for the year :) 这表示该年份最多可允许9999 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM