簡體   English   中英

正則表達式:在2個項目之間匹配文本

[英]Regex: match text between 2 items

我將如何匹配以下代碼以獲取兩個字符串:

  1. 第三個標題關閉標簽
  2. 第6個標題的第2個標題關閉標簽(依此類推...第9個標題的第3個標題關閉標簽等)

這是要匹配的字符串:

title
<a></a>
content here
<a></a>
text...
<a></a>
text...
title 
<a></a>
<a></a>
<a></a>

我嘗試使用。*,但這從標題到最后一個標簽捕獲了文本。

from re import findall, DOTALL

text = '''
title
<a></a>
content here
<a></a>
text...
<a></a>
text...
title 
<a></a>
<a></a>
<a></a>
'''
print findall(r'title.*?</a>.*?</a>.*?</a>', text, DOTALL)

['title\n<a></a>\ncontent here\n<a></a>\ntext...\n<a></a>', 'title \n<a></a>\n<a></a>\n<a></a>']

你也可以使用

print findall(r'title(?:.*?</a>){3}', text, DOTALL)

通常*是貪婪的,而*? 不情願。 嘗試將.*替換為.*?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM