Given a string "Time Remaining: 2 min 25 sec"
, how do we use Python's re
regex method to extract 2
and 25
?
Tried the following but only managed to extract 2
but not 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"
CodePudding user response:
I would use re.findall
here, with an actual pattern which matches the entire input:
time_remaining = "Time Remaining: 2 min 25 sec"
matches = re.findall(r'(\d ) min (\d ) sec\b', time_remaining)
print(matches) # [('2', '25')]
The problem with your current pattern is that it uses zero width lookaheads to match the min
and sec
markers.