How To Resolve An Unexpected Quantifier In Javascript Regex Pattern?
Scenario: I've added a client side url validator using the following regex pattern. The pattern is supposed to check whether the URL input matches. ^(?#Protocol)(?:(?:ht|f)tp(?:s?
Solution 1:
JS regex does not support comments like (?#...)
that can be used in regex flavors that support freespace (/x
, verbose) mode, you need to remove all of them.
Use
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;
See demo
I also suggest adding a /i
case-insensitive modifier.
The only advantage of using a RegExp constructor is that you can easily add comments to blocks of this expression. Then use:
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");
Post a Comment for "How To Resolve An Unexpected Quantifier In Javascript Regex Pattern?"