Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

javascript - 什么是匹配URL的良好正则表达式? [重复](What is a good regular expression to match a URL? [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

Currently I have an input box which will detect the URL and parse the data.(目前,我有一个输入框,它将检测URL并解析数据。)

So right now, I am using:(所以现在,我正在使用:)

var urlR = /^(?:([A-Za-z]+):)?(/{0,3})([0-9.-A-Za-z]+)
           (?::(d+))?(?:/([^?#]*))?(?:?([^#]*))?(?:#(.*))?$/;
var url= content.match(urlR);

The problem is, when I enter a URL like www.google.com , its not working.(问题是,当我输入www.google.com类的URL时,它不起作用。)

when I entered http://www.google.com , it is working.(当我输入http://www.google.com ,它正在工作。)

I am not very fluent in regular expressions.(我不太会使用正则表达式。)

Can anyone help me?(谁能帮我?)   ask by bigbob translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Regex if you want to ensure URL starts with HTTP/HTTPS:(正则表达式是否要确保URL以HTTP / HTTPS开头:)

https?://(www.)?[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&//=]*)

If you do not require HTTP protocol:(如果您不需要HTTP协议:)

[-a-zA-Z0-9@:%._+~#=]{1,256}.[a-zA-Z0-9()]{1,6}([-a-zA-Z0-9()@:%_+.~#?&//=]*)

To try this out see http://regexr.com?37i6s , or for a version which is less restrictive http://regexr.com/3e6m0 .(要尝试此操作,请访问http://regexr.com?37i6s ,或使用限制性较弱的http://regexr.com/3e6m0版本。)

Example JavaScript implementation:(JavaScript实现示例:)

 var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-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"); } 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...