简体   繁体   English

Javascript正则表达式直到字符串结尾才匹配

[英]Javascript regular expression does not match till the end of the string

I am validating dates using regular expression in javascript. 我在javascript中使用正则表达式验证日期。 The regular expression I am using is 我正在使用的正则表达式是

/^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$/

This matches dates accurately but it would match values such as 1/1/2001ff even though I am using $ to mark the end of string. 这准确地匹配日期但它会匹配诸如1/1 / 2001ff之类的值,即使我使用$来标记字符串的结尾。 But if I give values like ff1/1/2001 it would invalidate it. 但是,如果我给出像ff1 / 1/2001这样的值,它会使它无效。 So it's considering the start of the string and ignore the end of string part. 所以它正在考虑字符串的开头并忽略字符串部分的结尾。

Does anyone know the reason for this. 有谁知道这个的原因。

From: Detecting an "invalid date" Date instance in JavaScript 发件人: 在JavaScript中检测“无效日期”日期实例

if ( Object.prototype.toString.call(d) === "[object Date]" ) {
  // it is a date
  if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
    // date is not valid
  }
  else {
    // date is valid
  }
}
else {
  // not a date
}

Logically, it makes much more sense to check if the date is valid rather than using a regex to match a date. 从逻辑上讲,检查日期是否有效而不是使用正则表达式来匹配日期更有意义。 However, if you're trying to search for dates, your regex still works (I tested it in Notepad++ find for example.) Other than that, like the comment said, there's no reason to have such a complicated regex. 但是,如果您正在尝试搜索日期,那么您的正则表达式仍然有效(我在Notepad ++中进行了测试,例如。)除此之外,就像评论所说的那样,没有理由拥有如此复杂的正则表达式。

As correctly pointed out by Dracs, the issue was with missing brackets. 正如Dracs正确指出的那样,问题是缺少括号。 Thank you very much for pointing that out. 非常感谢您指出这一点。 The reason for not using javascript date object is we need only to allow mm/dd/yyyy format in the textbox. 不使用javascript日期对象的原因是我们只需要在文本框中允许mm / dd / yyyy格式。 So it would be easy to use a regex to validate textbox. 因此,使用正则表达式来验证文本框会很容易。

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

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