[英]Python Regex extract Minutes and Seconds
给定一个字符串"Time Remaining: 2 min 25 sec"
,我们如何使用 Python 的re
regex 方法来提取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"
我会在这里使用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
标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.