情境: 我使用以下正则表达式模式添加了客户端URL验证器。该模式应该检查URL输入是否匹配。
# TYPE DATABASE USER ADDRESS METHOD
local all all md5
问题:
当我通过IE调试^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$
JavaScript方法时,会抛出ValidateOtherInstituteWebsite
错误。
检查:
我在C#服务器端验证方法中实现了相同的正则表达式,没有错误,正则表达式匹配正确。从研究错误来看,编译器似乎是interpreting some of the regex as code,但我看不到。
问题:
如何编辑此正则表达式模式以使用JavaScript?
代码:
JavaScript runtime error - unexpected quantifier
异常屏幕截图:
答案 0 :(得分:1)
JS regex不支持可以在支持freespace((?#...)
,verbose)模式的正则表达式中使用的/x
之类的注释,您需要删除所有这些注释。
使用
var urlValidationRegex = /^(?:(?:ht|f)tp(?:s?):\/\/|~\/|\/)?(?:\w+:\w+@)?(?:(?:[-\w]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$/i;
请参阅demo
我还建议添加/i
不区分大小写的修饰符。
使用RegExp构造函数的唯一优点是您可以轻松地向此表达式的块添加注释。然后使用:
var urlValidationRegex = RegExp("^" +
"(?:(?:ht|f)tps?://|~?/)?" + // Protocol
"(?:\\w+:\\w+@)?" + //Username:Password
"(?:(?:[-\\w]+\\.)+" + //Subdomains
"(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))" + //TopLevel Domains
"(?::\\d{1,5})?" + //Port
"(?:(?:(?:/(?:[-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|/)+|\\?|#)?" + //Directories
"(?:(?:\\?(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)(?:&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + //Query
"(?:#(?:[-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?$" //Anchor
);
document.body.innerHTML = urlValidationRegex.test("000");
document.body.innerHTML +="<br/>"+ urlValidationRegex.test("http://stackoverflow.com/questions/35089817/how-to-resolve-an-unexpected-quantifier-in-javascript-regex-pattern/35089871?noredirect=1#comment57910001_35089871");