【问题标题】:How do I match only the main part of the URL with regex?如何仅将 URL 的主要部分与正则表达式匹配?
【发布时间】:2020-03-30 01:52:07
【问题描述】:

努力想出一种巧妙的方法来匹配以下所有粗体字词。应该排除所有前导和尾随括号,并且不匹配实际页面 url 之外的任何内容,无论是提供原始的、带有域等的。本质上是一个文本框,人们可以在其中以他们想要的任何有效方式输入 url,我们只想获得实际页面它代表我们的网站。

https://www.example.com/page-words/

http://www.example.com/page-other-words/

www.example.com/页面/另一个页面

更多页面/更多/

example.com/page-more-words/

/文档/

/文字

测试

其他/

【问题讨论】:

  • 您使用哪种语言?
  • 有 URL 解析器会为你做这件事。取决于您使用的语言,但这里没有必要使用正则表达式。
  • 也许:regex101.com/r/h0Cohs/1 在第 2 组中被捕获
  • @MDR - 完美!谢谢!如果您作为答案提交,我可以标记为解决方案吗?我将在 python 中实现它,但我只是在寻找原始的正则表达式,所以我不必只依赖任何 python。
  • @Miles np。完毕。很高兴它有帮助。

标签: regex


【解决方案1】:

鉴于这些字符串...

https://www.example.com/page-words/

http://www.example.com/page-other-words/

www.example.com/page/another-page

more-page/some-more/

example.com/page-more-words/

/doc/

/text

test

other/

试试这个正则表达式...

^(.*?.com\/|\/)?(.*?)(\/)?$

演示(网站解释右侧栏上的正则表达式):https://regex101.com/r/h0Cohs/1

所需的子字符串在 $2(Python 中为 \2)中捕获,因此您可以只捕获:

page-words

page-other-words

page/another-page

more-page/some-more

page-more-words

doc

text

test

other

【讨论】:

  • 如果还有一个 html,(例如 www.example.com/page/another-page.html )我为自己更新 MDR 的公式:^(.*?.com\/|\/)?(.*?)(\/)?(\.html)?$
猜你喜欢
  • 1970-01-01
  • 2012-03-24
  • 2015-04-12
  • 1970-01-01
  • 2020-01-02
  • 2012-03-18
  • 2019-03-07
  • 2019-03-08
相关资源
最近更新 更多