繁体   English   中英

如何使用正则表达式匹配没有顶级域名的链接?

[英]How to match links without top-level domain using regex?

我使用下一个正则表达式(linkify regex的更新版本)来匹配链接,而不匹配电子邮件。

(\s*|[^a-zA-Z0-9.\+_\/"\>\-]|^)(?:([a-zA-Z0-9\+_\-]+(?:\.[a-zA-Z0-9\+_\-]+)*@)?(http:\/\/|https:\/\/|ftp:\/\/|scp:\/\/){1}?((?:(?:[a-zA-Z0-9][a-zA-Z0-9_%\-_+]*\.)+))(?:[a-zA-Z]{2,})((?::\d{1,5}))?((?:[\/|\?](?:[\-a-zA-Z0-9_%#*&+=~!?,;:.\/]*)*)[\-\/a-zA-Z0-9_%#*&+=~]|\/?)?)([^a-zA-Z0-9\+_\/"\<\-]|$)

但是,此正则表达式找不到类似以下的网址: https://someurl:3333/view/something

你能帮我吗? 谢谢!

这应该是表达式的“最少修改”版本,以匹配没有顶级域名的域:

(\s*|[^a-zA-Z0-9.\+_\/"\>\-]|^)(?:([a-zA-Z0-9\+_\-]+(?:\.[a-zA-Z0-9\+_\-]+)*@)?(http:\/\/|https:\/\/|ftp:\/\/|scp:\/\/){1}?((?:[a-zA-Z0-9][a-zA-Z0-9_%\-_+.]*)(?:\.[a-zA-Z]{2,})?)((?::\d{1,5}))?((?:[\/|\?](?:[\-a-zA-Z0-9_%#*&+=~!?,;:.\/]*)*)[\-\/a-zA-Z0-9_%#*&+=~]|\/?)?)([^a-zA-Z0-9\+_\/"\<\-]|$)

更改的部分是捕获组3,这是夺取域的部分。 它来自:

(
 (?:
  (?:
   [a-zA-Z0-9]
   [a-zA-Z0-9_%\-_+]*
   \.
  )+                  (?# this is how they repeated for optional subdomains)
 )
)
(?:
 [a-zA-Z]{2,}         (?# here is the mandatory TLD)
)

对此:

(
 (?:
  [a-zA-Z0-9]
  [a-zA-Z0-9_%\-_+.]* (?# the . is in the character class here for subdomains)
 )
 (?:
  \.
  [a-zA-Z]{2,}
 )?                   (?# this TLD is optional)
)

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM