user15278135
user15278135

Reputation: 111

how to use regex to search for a float pattern inside a list

So I have the following list of data:

lst_text = ['---', 'Project-Desc: kytos/kytos-end-to-end-tester', 'Last-Status: failed', 'pytest summary:  12 failed, 49 passed in 2919.10 seconds ']

I need to extract the "2919.10 seconds" from there.

I have this code :

summary = re.findall(r"\d+ \w+", lst_text[3])

So far, the regex that extracts the summary does not account for decimal points and also expects a space between a number and word. That current line of code just returns "10".

However, I need to recheck the regex expression, so that it also includes floating point numbers.

Any suggestions?

Upvotes: 0

Views: 916

Answers (1)

The fourth bird
The fourth bird

Reputation: 163467

To get the floating point value followed by the word after from the fourth item in the list:

\b\d+\.\d+\s+\w+
  • \b A word boundary to prevent a partial match
  • \d+\.\d+ Match 1+ digits, a . and 1+ digits
  • \s+\w+ Match 1+ whitespace chars and 1+ word chars

Updated example code

import re
lst_text = ['---', 'Project-Desc: kytos/kytos-end-to-end-tester', 'Last-Status: failed', 'pytest summary:  12 failed, 49 passed in 2919.10 seconds ']
summary = re.findall(r"\b\d+\.\d+\s+\w+", lst_text[3])
print(summary)

Note that \w can also match a digit, so 2919.10 12345 would for example also match.

Output

['2919.10 seconds']

Upvotes: 2

Related Questions