正则表达式找不到两个匹配项

2024-05-18 21:41:44 发布

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

我在Python中有一个正则表达式:

p = re.compile("<" + tag + ">([aA-zZ0-9\-\s:]*)</" + tag + ">")

而且我似乎无法让它在这个字符串中找到两个匹配项(其中标记是'unique')

<unique>UNIQUE Passive - Maim:</unique> Basic attacks deal 10 bonus magic damage to monsters on hit.<br><unique>UNIQUE Passive - Butcher:</unique> Damage dealt to monsters increased by 10%.<br><br><i>ique Passives with the same name don't stack.)</i>

你知道为什么它只和第一个匹配吗?你知道吗


Tags: to字符串标记brrebasictagaa
1条回答
网友
1楼 · 发布于 2024-05-18 21:41:44

如果您使用p.search,请使用findall或finditer代替它。你知道吗

import re
tag = 'unique'
# p = re.compile("<" + tag + ">([aA-zZ0-9\-\s:]*)</" + tag + ">")
# aA-zZ means a, range A-z and Z. this includes some sign like '[', '^' ... .
# the last '-' in character group( inside [ and ] ) matches '-' self.
p = re.compile("<" + tag + ">([a-zA-Z0-9\s:-]*)</" + tag + ">")

ml = "<unique>UNIQUE Passive - Maim:</unique> Basic attacks deal 10 bonus magic damage to monsters on hit.<br><unique>UNIQUE Passive - Butcher:</unique> Damage dealt to monsters increased by 10%.<br><br><i>ique Passives with the same name don't stack.)</i>"
m = p.search(ml)
print m.group()
print

print p.findall(ml)
print

for m in p.finditer(ml):
    print m.group()

输出:

<unique>UNIQUE Passive - Maim:</unique>

['UNIQUE Passive - Maim:', 'UNIQUE Passive - Butcher:']

<unique>UNIQUE Passive - Maim:</unique>
<unique>UNIQUE Passive - Butcher:</unique>

相关问题 更多 >

    热门问题