简体   繁体   English

如何使用javascript中的regexp解决“无效量词”错误?

[英]How do I resolve an “invalid quantifier” error with regexp in javascript?

I'm trying to transfer the following URL validation function from my PHP code to my javascript code: 我正在尝试将以下URL验证功能从我的PHP代码转移到我的JavaScript代码:

   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? 我怎样才能解决这个问题?

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 : 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. ) ,而无需引用该组的匹配项。

由于反斜杠是JavaScript中的转义字符,你必须逃脱它写在一个字符串:

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+)*)?");

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

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