Python regex:一行中有多个匹配项(使用findall())

2024-09-30 04:34:21 发布

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

我在文本中寻找这些“标记”:{t d="var1"}var2{/t}或{} 可以有更多的属性,只有“d”是必需的:{t d="var1" foo="bar"}var2{/t}

我的问题是-如果一行上有更多的标记,只返回一个结果,而不是所有的结果。返回的内容(从下面的测试字符串): (u'single1', u'Required item3')

我希望得到的回报: (u'single1', u'required1') (u'single2', u'Required item2') (u'single3', u'Required item3') 我被这个困住了。它每行只能使用一个标记,但不能每行使用多个标记。在

# -*- coding: UTF-8 -*-
import re

test_string = u'''
<span><img src="img/ico/required.png" class="icon" alt="{t d="single1"}required1{/t}" title="{t d="single2"}Required item2{/t}" /> {t d="single3"}Required item3{/t}</span>
'''


re_pattern = '''
    \{t[ ]{1}       # start tag name
    d="         # "d" attribute
    ([a-zA-Z0-9]*)      # "d" attribute content
    ".*\}       # end of "d" attribute
    (.+)        # tag content
    \{/t\}      # end tag
'''
rec_pattern = re.compile(re_pattern, re.VERBOSE)

res = rec_pattern.findall(test_string)
if res is not None:
    for item in res:
        print item

Tags: 标记retagrequiredattributerespatternvar1
1条回答
网友
1楼 · 发布于 2024-09-30 04:34:21

你的通配符太贪婪了。将它们从.*改为.*?,这样它们就不会贪心了:

re_pattern = '''
    \{t[ ]{1}           # start tag name
    d="                 # "d" attribute
    ([a-zA-Z0-9]*)      # "d" attribute content
    ".*?\}              # end of "d" attribute
    (.+?)               # tag content
    \{/t\}              # end tag
'''

相关问题 更多 >

    热门问题