【发布时间】:2020-05-28 06:59:18
【问题描述】:
我有一个正则表达式,我试图找到所有的 url 来创建链接 () 但我有以下问题:
- 某些带有“\foo\bar”的网址无法获取
- 网址将其作为网络的一部分。
www.foo.com -> https://mywebsite.com/section/www.foo.com
如果是没有https的链接有可能会自动放上去(避免ftp或者\hostname或者\ip)???
谢谢!
实时正则表达式: https://regex101.com/r/w3o9w1/1
正则表达式:
/(?:(?:https?|ftp|):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?/gm
文字演示:
text www.example.com text text text http://example.com
\\hadgs01\test2
http://192.168.1.1:3000/
192.168.1.1:3000
\\192.168.10.10\test\test.txt
http://example.com
http://example.gl
http://www.example.com
https://example.com
https://www.example.com
https://www.example.com/
https://www.example.com/bar
https://example.com/icons?d=bar&q=bar
http://abc.dec.ed.example.com
http://example.gl/1 http://example.gl/2
foo (http://example.gl/1) http://example.gl/(2)
http://example.com/. http://example.com/! http://example.com/,
example.gl/1
http://example.com/review/abc-def-ghi/?ct=t(test_test_bar)
www.example.com.au
http://www.example.com.au
http://www.example.com.au/ersdfs
http://www.example.com.au/bar?dfd=test@s=1
http://www.example.com:81/bar.html
代码:
var regex_links = /(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?/gm;
$(".text_to_replace").html($(".text_to_replace").html().replace(regex_links, " <a href=\"$&\" target='_blank'>$&</a> "));
【问题讨论】:
-
@Mandy8055 nope "\\hadgs01\test2" 或 "\\192.168.10.10\test\test.tx" 没有包含
-
@Mandy8055 "192.168.178.11/asd" -> "https://192.168.178.11/asd" 没有忽略 ftp 协议 :/ ,我可以这样做 if($1 != 'ftp') ??
-
@Mandy8055 是的,如果我没有协议,我会给它 https,如果我有 "\\example\" 我什么都不做
-
我认为有空格时最好忽略。
-
@Mandy8055 我刚刚将它改编为 jquery,如果它适用于我,唯一缺少的是“\\192.168.10.10\test\test.txt”和“\\hadgs01\test2”谢谢!
标签: javascript regex