我正在嘗試使用以下代碼對 URL 的部分進行分組和匹配:
pattern = '(http|https\:\/\/)([a-zA-Z0-9\-\.] \.)([a-zA-Z]{2,3})'
re.search(pattern, 'https://www.university.edu/').groups()
# what I got is ('https://', 'www.university.', 'edu')
# but what I expect is ('https://', 'www.university', 'edu')
如上所示,對于第二部分,目前我只能得到字符加 a .,但是如何更改我的代碼以便第二部分中沒有點?
謝謝!
uj5u.com熱心網友回復:
import re
pattern = '(http|https:\/\/)([a-zA-Z0-9\-\.] )\.([a-zA-Z]{2,3})'
print(re.search(pattern, 'https://www.university.edu/').groups())
uj5u.com熱心網友回復:
您可以使用findall以下正則運算式,并設定通用 ( g)、多行 ( m) 和大小寫無關 ( i) 標志:
^https?:\/\/|[a-z\d .-] (?=\.)|(?<=\.)[a-z]{2,3}(?=\/?$)
正則運算式演示< ˉ\ (ツ) /ˉ > Python 演示
請注意,正則運算式演示鏈接中的最后一個示例說明此運算式不檢查字串格式的正確性。這無疑是@DeepSpace 對這個問題發表評論的原因之一。
運算式可以分解如下(或者,將游標懸停在正則運算式鏈接處的運算式的每個元素上以獲得對其功能的解釋)。
^http # match a literal
s? # optionally match 's'
:\/\/ # match a literal
| # or
[a-z\d .-] # match one or more of the indicated characters
(?=\.) # positive lookahead asserts that previous match is
# followed by a period
| # or
[a-z]{2,3} # match two or three letters
(?=\/?$) # positive lookahead asserts previous match is
# followed by '/' at the end of the line or
# by the end of the line
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/354301.html
上一篇:決議部分url-python
下一篇:從制表符分隔的檔案中提取數字
