[英]Regex to match url directory path without match file name
我想要一個匹配的正則表達式
https://example.com/studio/
或https://example.com/studio
不匹配https://example.com/studio/path-to-file-blah-blah
或https://example.com/studio/path-to-file-blah-blah.html
我嘗試https?:\\/\\/(?:w{3}[.])?example[.]com\\/studio\\S*
但它匹配上面的兩個組。
我也試過https?:\\/\\/(?:w{3}[.])?example[.]com\\/studio\\/?
它只能匹配第一組。 但問題是只匹配第二組。 請問我該怎么做?
我假設您需要從非結構化文本中解析 URL。 假設有一個空格字符、換行符或字符串的結尾,以下內容應該適合您。 如果在 URL 之后直接有句點或其他字符,這將失敗,但很容易修改以支持其他終止字符。
https?:\/\/(?:w{3}[.])?example[.]com\/studio\/?(?:\s|$)
(?:\\s|$)
只是說匹配一個空格字符(包括行結束行一個新行字符)或匹配字符串的結尾。
編輯
我想你說的第 2 組是:
https://example.com/studio/path-to-file-blah-blah
https://example.com/studio/path-to-file-blah-blah.html
要匹配這些,您需要以下正則表達式:
https?:\/\/(?:w{3}[.])?example[.]com\/studio\/\S+
我所做的唯一更改是最后一個字符是\\S*
,但它應該是\\S+
。
*
表示 0 或更多
+
表示 1 個或多個。
希望這涉及您正在尋找的內容。 如果我仍然不在,如果你給組貼上標簽,它會幫助我理解,這樣我就可以寫出正確的正則表達式。
進一步擴展 Nathan 的答案,您可以更改 RegEx 的末尾以不捕獲尾隨空格或換行符。 這將匹配前兩種情況:
https?:\/\/(?:w{3}[.])?example[.]com\/studio\/?(?=\s|$)
要僅匹配第二種情況,請使用以下命令:
https?:\/\/(?:w{3}[.])?example[.]com\/studio(?=[^\/])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.