Python regex match the third line containing a float

Question:

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?

Asked By: Jin

||

Answers:

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
Answered By: Wiktor Stribiżew

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
Answered By: gog
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.