使用正则表达式解析 URL

Jud*_*ang -1 python regex conditional-statements

我试图在我的正则表达式中结合 if else ,基本上如果字符串中存在某些模式,则捕获一种模式,如果没有,则捕获另一种模式。

字符串是:' https://www.searchpage.com/searchcompany.aspx?companyId=41490234&page=0&leftlink=true ”,我想提取'?

因此,如果 '?' 在字符串中检测到,正则表达式应该捕获 '?' 之后的所有内容。标记; 如果没有,则从头开始捕获。

我用过:'(.*\?.*)?(\?.*&.*)|(^&.*)' 但它没有用...

有什么建议吗?

谢谢!

Pet*_*ood 5

使用urlparse

>>> import urlparse
>>> parse_result = urlparse.urlparse('https://www.searchpage.com/searchcompany.aspx?
companyId=41490234&page=0&leftlink=true')

>>> parse_result
ParseResult(scheme='https', netloc='www.searchpage.com', 
path='/searchcompany.aspx', params='', 
query='companyId=41490234&page=0&leftlink=true', fragment='')

>>> urlparse.parse_qs(parse_result.query)
{'leftlink': ['true'], 'page': ['0'], 'companyId': ['41490234']}
Run Code Online (Sandbox Code Playgroud)

最后一行是键/值对的字典。