regex - 如何使以下正则表达式也匹配

标签 regex

我有以下正则表达式:

/^(https?:\/\/)(.+\.)?(.+)(\..*)$/gm

名单是:

https://localhost
https://www.example.com
https://www.subdomain.example.com
https://example.com
http://example.com
http://example..com
http://....example.com

匹配:

https://www.example.com
https://www.subdomain.example.com
https://example.com
http://example.com
http://example..com
http://....example.com

问题是,我想匹配https://localhost,我不想匹配:

http://example..com
http://....example.com

为什么我不只使用 /^https?:\/\/.+$/gm?因为我需要分组捕捉它们。因此,我的意思是:

对于 https://www.subdomain.example.com

Group 1: https://
Group 2: www.subdomain.
Group 3: example
Group 4: .com

对于 https://localhost,它会是:

Group 1: https://
Group 3: localhost

对于https://www.example.com:

Group 1: https://
Group 2: www.
Group 3: example
Group 4: .com

所以,在:

https://localhost
https://www.example.com
https://www.subdomain.example.com
https://example.com
http://example.com
http://example..com
http://....example.com

我只想匹配:

https://localhost
https://www.example.com
https://www.subdomain.example.com
https://example.com
http://example.com

顺便说一句,它不应该匹配无效的网址:

http:
https://

只有完整的网址。

顺便说一句,任何子域。

这是一个链接:https://regex101.com/r/z7V33F/1

我怎样才能做到这一点?

最佳答案

你可以使用这个正则表达式:

^(https?://)((?:[\w-]+\.){0,2}?)([^.]+)(\.[^.]+)?$

RegEx Demo

正则表达式详细信息:

  • ^ : 开始
  • (https?://) : 匹配 https://http://并在第 1 组中捕获
  • ((?:[\w-]+\.){0,2}?) : 匹配域的第一部分并在 optional group #2
  • 中捕获
  • ([^.]+) : 匹配域名的第 (last-1) 部分并在第 3 组中捕获
  • (\.[^.]+)? : 匹配域的最后一部分并在 *optional& group #4 中捕获
  • $ : 结束

关于regex - 如何使以下正则表达式也匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66103906/

相关文章:

regex - 用正则表达式替换csv中的千位分隔符

regex - 我需要一个正则表达式来查找 622126-622925 之间的范围

java - 正则表达式在测试工具中有效,但在生产环境中不匹配

regex - 使用 linux 将正则表达式匹配转换为大写

第一个括号之间的 Javascript 正则表达式字符串,包括括号内

javascript - 多行正则表达式无法正常工作

javascript - 正则表达式 -/\w\b\w/

regex - 对匹配的子字符串应用正则表达式

regex - 范围内的字符类-Vim

java - 正则表达式不会从字符串中删除字符