使用正则表达式分析URL

2024-06-23 03:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

字符串是: 'https://www.searchpage.com/searchcompany.aspx?companyId=41490234&page=0&leftlink=true“我想提取'?”周围的职员在

所以如果“?”如果在字符串中检测到,则正则表达式应捕获“?”后的所有内容如果没有,那就从头开始。在

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

有什么建议吗?在

谢谢!在


Tags: 字符串httpscomtrueifwwwpage模式
3条回答

使用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']}

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

此正则表达式:

(^[^?]*$|(?<=\?).*)

捕获:

  • ^[^?]*$所有内容,如果没有?,或者
  • (?<=\?).*?之后的所有内容(如果有)

但是,如果您使用的是url,则应该研究^{}(python3)或{a2}(python2)。在

regex可能不是解决这个问题的最佳解决方案…为什么不只是

my_url.split("?",1)

如果这真的是你想要做的

或者像其他人建议的那样

from urlparse import urlparse
print urlparse(my_url)

相关问题 更多 >

    热门问题