正则表达式中的多重分组
我有一个字符串
s="<response>blabla
<head> blabla
<t> EXTRACT 1</t>
<t>EXTRACT 2</t>
</head>
<body> blabla
<t>BODY 1</t>
<t>BODY 2</t>
</response>"
,我需要提取标签之间的文本,但前提是它位于头部。 我尝试了
regex="(?:
re.findall(regex,s)
但它也在获取正文部分,我知道我需要告诉它在结束头标签处停止,但我想不出任何方法
PS:字符串在一行中,我将其拆分以提高可读性。我想做这使用正则表达式而不是 xml 解析器。
I have a string
s="<response>blabla
<head> blabla
<t> EXTRACT 1</t>
<t>EXTRACT 2</t>
</head>
<body> blabla
<t>BODY 1</t>
<t>BODY 2</t>
</response>"
I need to extract the text betwen the tags and but only if its in the head part.
I tried
regex="(?:<t>([\w.,_]*)*)</t>
re.findall(regex,s)
but it is fetching the body part too , i understand that i need to tell it to stop at the closing head tag but I couldnt come up with any way
PS:The string is in a single line, I split it for better readability.And i want to do this using regex and not xml parsers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以先找到标头:
这给出:
[' blabla;摘录 1提取 2 ']
然后从头脑中得到你想要的东西:
>>> ['提取1','提取2']
You can find the header first :
This gives :
[' blabla <t> EXTRACT 1</t> <t>EXTRACT 2</t> ']
Then get what you want from the head :
>>> [' EXTRACT 1', 'EXTRACT 2']
我从 @oriberu
regex=(\w+) ( ?=.*?)
I got the solution from @oriberu
regex=<t>(\w+)</t>(?=.*?</head>)