[英]Using RegEX to match URL pattern, invalid quantifier?
I am trying to use RegEX to match a URL pattern.我正在尝试使用 RegEX 来匹配 URL 模式。 I found an answer here: Check if a Javascript string is a url
我在这里找到了答案: 检查 Javascript 字符串是否为 url
Which pointed me to here: http://forums.devshed.com/javascript-development-115/regexp-to-match-url-pattern-493764.html这指向了我: http://forums.devshed.com/javascript-development-115/regexp-to-match-url-pattern-493764.html
Which gave me the following code(cut and pasted from devshed to here and to my script):这给了我以下代码(从 devshed 剪切并粘贴到这里和我的脚本):
function ValidURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
When I attempt to use it in Firefox 4.0, Firebug 1.7.3 gives me an invalid quantifier error at:当我尝试在 Firefox 4.0 中使用它时,Firebug 1.7.3 在以下位置给我一个无效的量词错误:
'(\#[-a-z\d_]*)?$','i'); // fragment locater
Does anyone have an idea on what the issue might be?有谁知道问题可能是什么?
From other searches on invalid quantifier, I believe that * is an issue but not sure what it might be.从对无效量词的其他搜索中,我认为 * 是一个问题,但不确定它可能是什么。 The string in question that I am using the function on when it gives me the error is:
当它给我错误时,我正在使用 function 的有问题的字符串是:
htp://localhost:1987/
ADDED COMMENT The fix suggested by agent-j at least removed the invalid quantifier issue.添加评论agent-j 建议的修复至少消除了无效量词问题。 thumbs up
竖起大拇指
However, it doesn't like the sample url above when done correctly:但是,如果正确完成,它不喜欢上面的示例 url:
http://localhost:1987/
The issue is with the port.问题出在端口上。 When I remove the port #, it likes localhost.
当我删除端口号时,它喜欢本地主机。
I use this and it seems to have worked fine:我使用它,它似乎运行良好:
var re = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
var isUrl = re.test(message);
You need to escape the first \
in here:您需要在这里转义第一个
\
:
'(\?[;&a-z\d%_.~+=-]*)?'
becomes变成
'(\\?[;&a-z\d%_.~+=-]*)?'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.