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

regex - How do I resolve an "invalid quantifier" error with regexp in javascript? - Stack Overflow

programmeradmin0浏览0评论

I'm trying to transfer the following URL validation function from my PHP code to my javascript code:

   this.validate_url = function(field)
    {
        var pattern = new RegExp("^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?");
        var val = $("#" + field).val();

        return pattern.test(val);
    }

And this gives me the error:

invalid quantifier ?w+=w+)?(&w+=w+)*)?

How can I fix this?

I'm trying to transfer the following URL validation function from my PHP code to my javascript code:

   this.validate_url = function(field)
    {
        var pattern = new RegExp("^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?");
        var val = $("#" + field).val();

        return pattern.test(val);
    }

And this gives me the error:

invalid quantifier ?w+=w+)?(&w+=w+)*)?

How can I fix this?

Share Improve this question edited May 7, 2011 at 3:12 KatieK 13.9k19 gold badges78 silver badges91 bronze badges asked Nov 29, 2009 at 22:31 AliAli 267k269 gold badges592 silver badges786 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You either need to escape the backslashes within the string declaration:

var pattern = new RegExp("^((ht|f)tp(s?)://|~/|/)?(\\w+:\\w+@)?([a-zA-Z]{1}([\\w-]+\\.)+(\\w{2,5}))(:\\d{1,5})?((/?\\w+/)+|/?)(\\w+\\.\\w{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?");

Or you use the regular expression literal syntax /expr/flags:

var pattern = /^((ht|f)tp(s?):\/\/|~\/|\/)?(\w+:\w+@)?([a-zA-Z]{1}([\w-]+\.)+(\w{2,5}))(:\d{1,5})?((\/?\w+\/)+|\/?)(\w+\.\w{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?/;

You should also try to use non-capturing groups (?:expr) where you don’t need to reference the match of that groups.

Since backslash is an escaping character in JavaScript, you'll have to escape that to write it in a string:

var pattern = new RegExp("^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?");
发布评论

评论列表(0)

  1. 暂无评论