简体   繁体   English

RegEx 仅匹配 URL 的第一部分并将其用作变量

[英]RegEx Match only first part of URL and use this as variable

Always been struggeling with RegEx, help is much appreciated.一直在与 RegEx 斗争,非常感谢帮助。 I want to match parts of a URL with Regex but cannot get my head around it.我想将 URL 的部分内容与正则表达式匹配,但无法理解它。

Domains are:域是:

https:// name .secondpart.thirdpart.com https://名称.secondpart.thirdpart.com

I want my regex to match我希望我的正则表达式匹配

name How would I achieve this?名称我将如何实现这一目标?

Started with (?<=^|\.) and (?<=^|\.)secondpart\.thirdpart\.com$ but it didn't work.(?<=^|\.)(?<=^|\.)secondpart\.thirdpart\.com$ ,但没有成功。

Note that I escaped the slashes using leading backslashes, assuming you use slash as your regex delimiter.请注意,假设您使用斜杠作为正则表达式定界符,我使用前导反斜杠对斜杠进行了转义。 If you use no or a different delimiter (eg #) you can just use / instead of \/ .如果您不使用或使用不同的分隔符(例如#),您可以只使用/而不是\/


If you only care about the first part, then如果你只关心第一部分,那么

^[^.:\/]+:\/\/([^.]+)

should do the trick.应该做的伎俩。

https://regex101.com/r/CXXOOD/1 https://regex101.com/r/CXXOOD/1


If you for also need to enforce a specific domain after that then capture it in a group like this如果您之后还需要强制执行特定域,则将其捕获到这样的组中

^[^.:\/]+:\/\/([^.]+)\.secondpart\.thirdpart\.com$

https://regex101.com/r/gjfYhC/1 https://regex101.com/r/gjfYhC/1


If you want to make sure that at exactly 3 parts come after the sub-domain part, but don't care what they are:如果您想确保在子域部分之后恰好有 3 个部分,但不关心它们是什么:

^[^.:\/]+:\/\/([^.]+)(?:\.[^.]+){3}$

https://regex101.com/r/lUYBkT/1 https://regex101.com/r/lUYBkT/1

As you tagged pcre, you can use:当你标记 pcre 时,你可以使用:

^https?://\K[^\s./]+

Explanation解释

  • ^ Start of string ^字符串开始
  • https?:// Match the protocol with an optional s https?://匹配带有可选s的协议
  • \K Forget what is matched so far \K忘记到目前为止匹配的内容
  • [^\s./]+ Match 1+ times a non whitespace char except . [^\s./]+匹配 1+ 次非空白字符,除了. and //

See a regex demo .请参阅正则表达式演示

You can use it,你可以使用它,

(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})

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

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