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

Regex fails in javascript - Stack Overflow

programmeradmin3浏览0评论

I have a following regex expression in javascript

var reg = new RegExp("^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$");
return this.optional(element) || (reg.test(value));

in my code reg.test(value) return false even on correct values: for instance 222 222 2222 or 222-222-2222. All regex testers(especially this one, which calls the same methods) show that regex matches the expression. What can be the problem?

I have a following regex expression in javascript

var reg = new RegExp("^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$");
return this.optional(element) || (reg.test(value));

in my code reg.test(value) return false even on correct values: for instance 222 222 2222 or 222-222-2222. All regex testers(especially this one, which calls the same methods) show that regex matches the expression. What can be the problem?

Share Improve this question asked Jun 1, 2012 at 21:23 valerii.sverdlikvalerii.sverdlik 5595 silver badges18 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 10

Try this:

var reg = /^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$/;
return this.optional(element) || (reg.test(value));

Or also:

var reg = new RegExp("^[(]?[2-9]\\d{2}[)]?[\\-. :]?[2-9]\\d{2}[\\-. :]?\\d{4}$");
return this.optional(element) || (reg.test(value));

The \s are being swallowed by the string literal.

You should use a regex literal instead:

var reg = /^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$/;

I see one potential cause of troubles: if you're creating a new Regular Expression using the RegExp function, you'll have to escape backslashes twice - once for the JavaScript engine, and once for the RegEx engine.

You can test if this is causing the troubles by doing

var reg = /^[(]?[2-9]\d{2}[)]?[\-. :]?[2-9]\d{2}[\-. :]?\d{4}$/;

You are taking the regex in as a string so all of the occurrences of \d should be \\d because when the regex string is sent to the interpreter the \d character is not interpreted as a \ and a d but just a d adding the extra slash escapes the other slash so the \\d is interpreted as a \ and a d. Also I suggest one other change, the [(] should be replaced with \\( because the character class only contains one character and therefore has no point.

发布评论

评论列表(0)

  1. 暂无评论