zzzbbx
zzzbbx

Reputation: 10131

searching multiple items with Python re

I am trying to extract hours, mins, seconds and mseconds from a txt file, that may or may not be present in a line. The format is "hh:mm:ss.ms". I know I should so something like this

int(re.search('(\d+):(\d+):(\d+).(\d+)', current_line).group(1)) 

but I don't know how to returns these four values to four different variables.

Upvotes: 0

Views: 214

Answers (2)

phihag
phihag

Reputation: 287775

You can call groups on the match object to get a tuple of groups, like this:

match = re.search('(\d+):(\d+):(\d+).(\d+)', current_line)
hour,minute,second,ms = map(int, match.groups())

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

Well, if you insist on doing it in one line:

hrs, min, sec, msec = (int(group) for group in re.search('(\d+):(\d+):(\d+).(\d+)', current_line).groups())

Upvotes: 2

Related Questions