以非reedy方式将特定文本前的文本与regex匹配

2024-03-29 07:37:20 发布

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

我有表格的文本

<span style="color:red;">hello</span> <span style="color:green;">world</span>

我想尝试根据helloworld文本匹配其中一个span标记。我试过这种形式:

(<span.*?)(?=world).*?<\/span>

使用lookahead,但它匹配整个字符串,而不仅仅是我要查找的<span style="color:green;">world</span>。如何以非贪婪的方式匹配<span...前面的world文本?你知道吗


Tags: 字符串标记文本helloworldstyle方式green
1条回答
网友
1楼 · 发布于 2024-03-29 07:37:20

您可以尝试以下正则表达式:

(<span[^>]*>)world.*?<\/span>

下面是一个Python代码片段,其中包含这个regex:

input = "<span style=\"color:red;\">hello</span> <span style=\"color:green;\">world</span>"

matchObj = re.match( r'.*(<span[^>]*>)world.*?</span>.*', input, re.M|re.I)

if matchObj:
    print "matchObj.group() : ", matchObj.group()
    print "matchObj.group(1) : ", matchObj.group(1)
else:
   print "No match!!"

注意,在Python代码中,我必须将.*添加到原始模式的开头和结尾,因为Python regex引擎似乎坚持将模式与整个字符串相匹配。可能会有一个标志来避免这种情况,但在任何情况下,希望这个答案能让你摆脱困境,让你继续你的工作。你知道吗

此处演示:

Rextester

相关问题 更多 >