问题描述
目前我有一个输入框,可以检测 URL 并解析数据.
Currently I have an input box which will detect the URL and parse the data.
所以现在,我正在使用:
So right now, I am using:
var urlR = /^(?:([A-Za-z]+):)?(/{0,3})([0-9.-A-Za-z]+)
(?::(d+))?(?:/([^?#]*))?(?:?([^#]*))?(?:#(.*))?$/;
var url= content.match(urlR);
问题是,当我输入像 www.google.com
这样的 URL 时,它不起作用.当我输入 http://www.google.com
时,它正在工作.
The problem is, when I enter a URL like www.google.com
, its not working. when I entered http://www.google.com
, it is working.
我对正则表达式不是很流利.有人可以帮我吗?
I am not very fluent in regular expressions. Can anyone help me?
推荐答案
Regex 如果你想确保 URL 以 HTTP/HTTPS 开头:
Regex if you want to ensure URL starts with HTTP/HTTPS:
https?://(www.)?[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&//=]*)
如果您不需要 HTTP 协议:
If you do not require HTTP protocol:
[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&//=]*)
要尝试此操作,请参阅 http://regexr.com?37i6s,或查看更少的版本限制性http://regexr.com/3e6m0.
To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.
示例 JavaScript 实现:
Example JavaScript implementation:
var expression = /[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = 'www.google.com';
if (t.match(regex)) {
alert("Successful match");
} else {
alert("No match");
}
这篇关于什么是匹配 URL 的好的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!