Regex可以将url与特定域正确匹配,并且还可以添加子域

问题描述 投票:0回答:1

我有以下正则表达式:

(^|^[^:]+:\/\/|[^\.]+\.)hello\.net

似乎适合大多数情况,例如:

http://hello.net
https://hello.net
http://www.hello.net
https://www.hello.net
http://domain.hello.net
https://solutions.hello.net
hello.net
www.hello.net

但是仍然与它不应该匹配的这个:

hello.net.domain.com

您可以在这里看到它:https://regex101.com/r/fBH112/1

我基本上是尝试检查网址是否是hello.net的一部分。因此hello.net和任何子域(例如sub.hello.net)都应该匹配。它也应该匹配hello.net/bye。所以hello.net之后的所有内容都不相关。

regex url subdomain
1个回答
1
投票

您可以通过在末尾添加(?:\/.*)?$来修正图案:

(^|^[^:]+:\/\/|[^.]+\.)hello\.net(?:\/.*)?$

请参见regex demo(?:\/.*)?$匹配/的可选序列以及任意0个或更多字符,然后匹配字符串的结尾。

您可能会考虑使用“更清洁”的模式,例如

^(?:\w+:\/\/)?(?:[^\/.]+\.)?hello\.net(?:\/.*)?$

请参见regex demo。详细信息:

  • [^-字符串开头
  • (?:\w+:\/\/)?-可选出现1个以上的字符字符,然后是://字符平方
  • [(?:[^\/.]+\.)?-除/.然后是.]之外的任意1个或多个字符的可选出现>
  • [hello\.net-hello.net
  • [(?:\/.*)?$-可选出现的/,然后是任何0+字符,然后是字符串的结尾
© www.soinside.com 2019 - 2024. All rights reserved.