Python匹配Regex在tester中工作,但在cons中不起作用

2024-09-27 18:23:11 发布

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

这很简单,但我好像搞不懂这个。我做错什么了?在

在线测试仪显示该方法工作正常: https://regex101.com/r/rpUNK9/3

但是当我在Python REPL中尝试时,没有得到任何返回:

test = """<speak><prosody volume=\"x-loud\">This text should match?<break time='500ms'/><mark name='punchline'/>\n\n<say-as interpret-as='interjection'>boing</say-as><break time='1ms'/>!\n</prosody></speak>"""
rex = '(?<=<speak><prosody volume=\\\"x-loud\\\">)(.*)(?=<\/prosody>(?:<metadata>|<\/speak>))'
m = re.search(rex,test)

Tags: 方法httpstestcomtimeasrexsay
1条回答
网友
1楼 · 发布于 2024-09-27 18:23:11

此问题与\n有关。此标记.*与新行不匹配,只要有新行,它就会中断。这段代码\n在pythonrepl中被解释为一个新行,但在regex101网站中被解释为常规文本。试着这样想你的绳子:

<speak><prosody volume=\"x-loud\">This text should match?<break time='500ms'/><mark name='punchline'/>

<say-as interpret-as='interjection'>boing</say-as><break time='1ms'/>!
</prosody></speak>

上面的字符串与当前的正则表达式代码不匹配。看看这里:https://regex101.com/r/rpUNK9/4

要解决这个问题,请将.*替换为可以匹配新行的内容,例如[\s\S]*

整个代码将是:

^{pr2}$

示例:https://regex101.com/r/rpUNK9/5

Python代码:

import re
test = """<speak><prosody volume=\"x-loud\">This text should match?<break time='500ms'/><mark name='punchline'/>\n\n<say-as interpret-as='interjection'>boing</say-as><break time='1ms'/>!\n</prosody></speak>"""
rex = '(?<=<speak><prosody volume=\\\"x-loud\\\">)([\s\S]*)(?=<\/prosody>(?:<metadata>|<\/speak>))'
m = re.search(rex,test)

相关问题 更多 >

    热门问题