[Python] Trying to use regex to extract "X =" value from a string [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I've recently started learning Python. I've even more recently come across regex. I've no previous coding experience.

    I'm trying to use regex to extract the float X value from a string:

    "blah, blah X = 1.788549774856667E+03 blah, blah".

    The X value can be formatted as above, or as X =-1.788549774856667E+03 (with no whitespace between the "=" and "-". That choice is what's confusing me. My question is, what is the correct regex, and why?

    This is the code I've used:

    import re

    str = "blah, blah X = 1.788549774856667E+03 blah, blah"
    x = float(re.findall("X = ([\d.]+E.\d+)", str)[0])

    print(x)


    This works when there is whitespace between the "=" and first digit of X. However, it doesn't work with "=-", with no whitespace between this and the first digit of X. I've tried using * (zero or more times) before "\d" but with no success.

    UPDATE 1

    The solution I came up with, which appears to work, is:

    X =([-|\s][\d.]+E.\d+)

    Continue reading...

Compartilhe esta Página