簡體   English   中英

如何僅將 URL 的主要部分與正則表達式匹配?

[英]How do I match only the main part of the URL with regex?

努力想出一種巧妙的方法來匹配以下所有粗體術語。 應該排除所有前導和尾隨括號,並且不匹配實際頁面 url 之外的任何內容,無論是否提供原始、域等。本質上是一個文本框,人們可以在其中以他們想要的任何有效方式輸入 url,我們只想獲取實際頁面它代表我們的網站。

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

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

www.example.com/頁/另一頁

更多頁面/更多/

example.com/ page-more-words /

/文檔/

/文字

測試

其他/

鑒於這些字符串...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM