匹配 URL 的正则表达式,网上能找到很多,很难找到完美的。按需使用吧。
版本一
(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]
IP地址、前后有汉字、带参数,都能匹配。缺点:类似 www.oxoox.com 不带协议的匹配不到。来源:申龙斌的程序人生
版本二
(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Za-z0-9+&@#/%=~_|$?!:,.]*\)|[-A-Za-z0-9+&@#/%=~_|$?!:,.])*(?:\([-A-Za-z0-9+&@#/%=~_|$?!:,.]*\)|[A-Za-z0-9+&@#/%=~_|$])
上面的改进版。参考:Detecting URLs in a Block of Text
版本三
(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
来源:Regular expression to find URLs within a string
正则表达式在线测试工具
RegExr 正则在线测试:https://regexr.com/
菜鸟工具正则在线测试:https://c.runoob.com/front-end/854
正则可视化:https://jex.im/regulex/
本文首发于:匹配 URL 的正则表达式-垃圾站
Comments:0