【问题标题】:regex with python / re.match doesn't work带有 python / re.match 的正则表达式不起作用
【发布时间】:2016-03-13 23:30:26
【问题描述】:

我有这样的 stringText

sText ="""<firstName name="hello morning" id="2342"/>
<mainDescription description="cooking food blog 5 years"/>
<special description="G10X, U16X, U17X, G26X, C32X, G34X, G37X, U39X, C40X, G46X,C49X, U54X, U55X, A58X"/> 
"""

我想收到:

烹饪美食博客 5 年

我尝试了许多不同的正则表达式

喜欢:

p = re.compile('<mainDescription description=\"([^\"]+)\"\/>')
print re.match(p, sText)

p = re.compile(ur'<mainDescription description="([^"]+)"\/>')

并使用 (.+) 根据regex101.com 我的正则表达式应该可以正常工作,但事实并非如此。 我不知道为什么

【问题讨论】:

    标签: python regex regex-negation regex-greedy


    【解决方案1】:

    尝试使用 findall():

    print re.findall('<mainDescription description=\"([^\"]+)\"\/>', sText)
    

    输出:

    ['cooking food blog 5 years']
    

    【讨论】:

    • Traceback(最近一次调用最后):文件“search_12.py”,第 10 行,在 中打印 re.search(p, sText).group(0) 文件“C:\Miniconda2 \lib\re.py",第 146 行,在搜索中返回 _compile(pattern, flags).search(string) TypeError: expected string or buffer
    • 对不起,我复制粘贴坏了一个 -> Traceback(最近一次调用最后):AttributeError:'NoneType'对象没有属性'组'
    • 试试只用 findall
    【解决方案2】:

    似乎是因为您使用的是re.match() 而不是re.search()re.match() 从字符串的开头搜索,而 re.search() 在任何地方搜索。这有效:

    sText ="""<firstName name="hello morning" id="2342"/>
    <mainDescription description="cooking food blog 5 years"/>
    <special description="G10X, U16X, U17X, G26X, C32X, G34X, G37X, U39X, C40X, G46X,C49X, U54X, U55X, A58X"/> 
    """
    p = re.compile('<mainDescription description=\"([^\"]+)\"\/>')
    print re.search(p, sText).group(1)
    

    顺便说一句,如果您使用的是',则不需要转义引号("),这意味着这就足够了:

    re.search('<mainDescription description="([^"]+)"/>', sText)
    

    【讨论】:

    • @PyLearn 不完全确定为什么它不适合你,但如果你复制粘贴我的代码,它应该可以工作:-/
    【解决方案3】:

    re.match 返回一个match 对象,您需要从中检索所需的组。

    sText ="""<firstName name="hello morning" id="2342"/>
    <mainDescription description="cooking food blog 5 years"/>
    <special description="G10X, U16X, U17X, G26X, C32X, G34X, G37X, U39X, C40X, G46X,C49X, U54X, U55X, A58X"/> 
    """
    r = re.compile("""<mainDescription description="(?P<description>[^"]+)"\/>""")
    m = r.match(sText)
    print m.group('description')
    

    请注意,也可以使用索引(在本例中为 0)访问组,但我更喜欢指定关键字。

    【讨论】:

    • AttributeError: 'NoneType' 对象没有属性 'group'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    相关资源
    最近更新 更多