給定一個字串"Time Remaining: 2 min 25 sec",我們如何使用 Python 的re正則運算式方法來提取2和25?
嘗試了以下但只能提取2而不是25.
import re
time_remaining = "Time Remaining: 2 min 25 sec"
pattern = "(?<=Time Remaining: )(.*)(?= min) (.*)(?= sec)"
matches = re.search(pattern, time_remaining)
if matches:
print(matches.group(1)) # Obtained: "2"
print(matches.group(2)) # Obtained: "min 25"
# Desired: "25"
uj5u.com熱心網友回復:
我會re.findall在這里使用一個與整個輸入匹配的實際模式:
time_remaining = "Time Remaining: 2 min 25 sec"
matches = re.findall(r'(\d ) min (\d ) sec\b', time_remaining)
print(matches) # [('2', '25')]
您當前模式的問題在于它使用零寬度前瞻來匹配min和sec標記。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350284.html
標籤:Python 蟒蛇-3.x 正则表达式 正则表达式组 蟒蛇正则表达式
上一篇:Python3.x中的字典和回圈
