Home > Blockchain >  Python regex match the third line containing a float
Python regex match the third line containing a float

Time:10-05

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related