使用Regex使用python解析URL的某些部分

2024-04-30 01:15:26 发布

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

假设我有如下几样东西

URL
http://hostname.com/as/ck$st=fa+gw+hw+ek+ei/
http://hostname.com/wqs/ck$st=fasd+/
http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav

我想检查url中的第一个+符号并向后移动,直到找到一个特殊字符,如/或?或=或任何其他特殊字符,并从该字符开始,一直到找到空格或行尾或&;或/

我在stackoverflow论坛的帮助下编写的正则表达式如下:

re.search(r"[^\w\+ ]([\w\+ ]+\+[\w\+ ]+)(?:[^\w\+ ]|$)", x).group(1)

这一个适用于第一行。但不解析第二行的任何内容。同样在第三行中,我想检查行中是否有像这样的多个模式。当前正则表达式只检查一种模式

我的输出应该是

parsed
fa+gw+hw+ek+ei
fasd
fa+gq+hf+kg+is gl+jh+ke+oj+kp

有人能帮我修改regex吗?它已经在那里了,可以满足这个需要吗

谢谢


Tags: comhttpashostnameckfastgw
3条回答

尝试使用urlparse失败后,获得所需信息的最佳方法似乎是使用正则表达式:

import urlparse
import re

urls = [
    "http://hostname.com/as/ck$st=fa+gw+hw+ek+ei/",
    "http://hostname.com/wqs/ck$st=fasd+/",
    "http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav"
]

for myurl in urls:
    parsed = urlparse.urlparse(myurl)

    print 'scheme  :', parsed.scheme
    print 'netloc  :', parsed.netloc
    print 'path    :', parsed.path
    print 'params  :', parsed.params
    print 'query   :', parsed.query
    print 'fragment:', parsed.fragment
    print 'username:', parsed.username
    print 'password:', parsed.password
    print 'hostname:', parsed.hostname, '(netloc in lower case)'
    print 'port    :', parsed.port

    print urlparse.parse_qs(parsed.query)

    print re.findall(r'([\w\+]+\+[\w\+]*)(?:[^\w\+]|$)', parsed.path)
    print '-' * 80

如果将[^\w\+ ]([\w\+ ]+\+[\w\+ ]+)(?:[^\w\+ ]|$)更改为[^\w\+ ]([\w\+ ]+\+[\w\+ ]*)(?:[^\w\+ ]|$),它也将匹配第二个URL

它将包含尾随的“+”,它没有包含在您想要的输出中,但是似乎符合您提到的标准,因此如果您不想要任何尾随的“+”,这可能需要一些修改

我使用regexr得出这个(regexr link):

([\w\+]*\+[\w\+]*)(?:[^\w\+]|$)

匹配项:

fa+gw+hw+ek+ei fasd+ fa+gq+hf+kg+is gl+jh+ke+oj+kp

编辑:请尝试改用re.findall,而不是使用re.search:

>>> s = "http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav"
>>> re.findall("([\w\+]+\+[\w\+]*)(?:[^\w\+]|$)", s)
['fa+gq+hf+kg+is', 'gl+jh+ke+oj+kp']

相关问题 更多 >