![](/img/trans.png)
[英]Python,how to extract text between two markers multiple times throughout text file?
[英]How to get the substring between two markers in Python multiple times?
我有以下代碼:
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
for i in s:
start = s.find('alt="') + len('alt="')
end = s.find('"/>')
substring = s[start:end]
print(substring)
但它只打印了很多次“Thunder Force”。 我希望它找到“Thunder Force”和“Godzilla vs. Kong”並分別打印這兩個。 如何?
你可以使用正則表達式
import re
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
x = re.findall(r'alt="(.*?)"/>', s)
print(x)
output
['Thunder Force', 'Godzilla vs. Kong']
使用regex
和re.findall()
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
print(re.findall(r'(?<=alt\=").*?(?="/>)', s))
#['Thunder Force', 'Godzilla vs. Kong']
這是一個非正則表達式解決方案,看起來更像我認為您嘗試通過發布的嘗試實現的目標:
start = 0
while True:
start = s.find('alt="', start)
if start == -1:
break
start += len('alt="')
end = s.find('"/>', start)
if end == -1:
break
substring = s[start:end]
start = end
print(substring)
您還可以使用否定字符 class [^"]+
來匹配除"
之外的任何字符,如果要匹配至少一個字符,請重復 1 次以上。
如果空匹配也可以,您可以使用*
而不是+
。
import re
s = '''alt="Thunder Force"/>ehkjehkljhiflealt="Godzilla vs. Kong"/>'''
x = re.findall(r'alt="([^"]+)"/>', s)
print(x)
Output
['Thunder Force', 'Godzilla vs. Kong']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.