最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Why do these javascript regex throw syntax errors? - Stack Overflow

programmeradmin5浏览0评论

I am trying to validate a text string as a date before processing it, however both of the regex i have tried are throwing syntax errors and I can't see why. From what I can tell there is nothing wrong with either. These are the strings:

 var datePattern1 = new RegExp( (0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-](19|20)\d\d );

and

var datePattern2 = new RegExp( [0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2} );

Appreciate any help.

I am trying to validate a text string as a date before processing it, however both of the regex i have tried are throwing syntax errors and I can't see why. From what I can tell there is nothing wrong with either. These are the strings:

 var datePattern1 = new RegExp( (0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-](19|20)\d\d );

and

var datePattern2 = new RegExp( [0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2} );

Appreciate any help.

Share Improve this question asked Mar 8, 2009 at 13:25 MalTuckerMalTucker 2691 gold badge5 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

You are missing the quotes around your expressions:

var datePattern1 = new RegExp( "(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-](19|20)\d\d" );
var datePattern2 = new RegExp( "[0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}" );

Either pass a string to the RegExp constructor as darin mentioned or use the RegExp syntax “/ … /”:

var datePattern1 = /(0[1-9]|1[012])[-](0[1-9]|[12][0-9]|3[01])[-](19|20)\d\d/;
var datePattern2 = /[0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}/;

The Regexp() constructor expects a string, so you need to quote your regex:

var datePattern2 = new RegExp('[0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}');

When using double quotes, watch out for backslash escapes in the regex. Alternatively, you can use the Perl syntax:

var datePattern2 = /[0-3][0-9]-(0|1)[0-9]-(19|20)[0-9]{2}/;
发布评论

评论列表(0)

  1. 暂无评论