Jin
Jin

Reputation: 47

Python regex match the third line containing a float

I have a list containing those 3 lines repeated n times:

Test
Choice : Q1
Expected : 0,5

The only value that differ into the list is the third line Expected : 0,5 the float number can differ from -10 to 10.

I haven't managed to come up with a regular expression to only get the float number inside the third line yet.

I'm not comfortable with regex, what I've managed to dot yet is something like this:

(?:^[^\n]*\n?)

Here is my regex demo.

Any good suggestion?

Upvotes: 0

Views: 80

Answers (2)

gog
gog

Reputation: 11347

You don't need a regex for a simple task like this:

>>> s = 'Expected : 0,5'
>>> value = s.split(':')[-1].strip()
>>> value
'0,5'

If you want it to be a float rather than a string:

>>> num_value = float(value.replace(',', '.'))
>>> num_value
0.5

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

You can use

\b[0-9]+(?:,[0-9]+)?\b

See the regex demo.

Details:

  • \b - a word boundary
  • [0-9]+ - one or more digits
  • (?:,[0-9]+)? - an optional sequence of a comma and one or more digits
  • \b - a word boundary

Upvotes: 1

Related Questions