尝试使用正则表达式匹配URL

时间:2017-10-14 14:34:00

标签: javascript regex

我正在尝试使用正则表达式匹配网址

https?:\/\/.*\..*

但是如果在URL之后出现空格,则无法理解如何结束匹配。

例如,在下面的图片中,对于最后一场比赛,我希望它在空间之前结束。 但似乎没有任何工作。

你能解释为什么在末尾添加\ b(单词边界)不起作用吗?

enter image description here

2 个答案:

答案 0 :(得分:3)

只需使用\S

https?:\/\/.*\.\S*

\S表示:匹配不是空格字符的所有内容(空格,制表符,分隔符...)

答案 1 :(得分:1)

使用lazy和非捕获组查看下面的解决方案:

在这里寻找更好的正则表达式' What is the best regular expression to check if a string is a valid URL?



//well let us dive into this:

var matches = document.querySelector("pre").textContent.match(/https?:\/\/.*\..*/g);

console.log(matches);

/*
your regex does the following
search for http:// or https://
then you want to search for every character that is not a newline until you find a dot
after that you simply search for everything that is not a newline.


you need lazy and a non-capturing group, lazy is ? - (?=\s)
*/

var matches2 = document.querySelector("pre").textContent.match(/https?:\/\/.+?\..+?(?=\s)/g);
console.log(matches2);

<pre>
foo@demo.net

http://foo.co.uk/
http://regexr.com/foo.html?q=bard
https://mediatemple.net jhjhjhjhjhjh
</pre>
&#13;
&#13;
&#13;