正则表达式中的多重分组

发布于 2025-01-10 14:19:15 字数 523 浏览 3 评论 0原文

我有一个字符串

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="(?:([\w.,_]*)*)

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云仙小弟 2025-01-17 14:19:15

您可以先找到标头:

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>"
pattern_head = "<head>(.*)</head>" 
header = re.findall(pattern_head, s)
print(header)

这给出: [' blabla;摘录 1提取 2']
然后从头脑中得到你想要的东西:

pattern = "<t>(.*?)</t>"
substring = re.findall(pattern,header[0])
print(substring)

>>> ['提取1','提取2']

You can find the header first :

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>"
pattern_head = "<head>(.*)</head>" 
header = re.findall(pattern_head, s)
print(header)

This gives : [' blabla <t> EXTRACT 1</t> <t>EXTRACT 2</t> ']
Then get what you want from the head :

pattern = "<t>(.*?)</t>"
substring = re.findall(pattern,header[0])
print(substring)

>>> [' EXTRACT 1', 'EXTRACT 2']

云之铃。 2025-01-17 14:19:15

我从 @oriberu

regex=(\w+)( ?=.*?)

I got the solution from @oriberu

regex=<t>(\w+)</t>(?=.*?</head>)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文