Python Regular Expression for validate numbers
Question: I want to create a regular expression for python snippet.

    
    
    import re
    pattern = "\d*\.?\d+[Ee]?[+-]?\d*"
    r = re.compile(pattern)
    txt = """
    12
    .12
    12.5
    12.5E4
    12.5e4
    12.4E+4
    12E4
    12e-4
    """
    x = r.findall(txt)
    print(x)
    

for filtering all valid input from txt this code is fine but invalid input
such as

> .12e, 12.3+4

are also allowed how can I fix this?


Answer: The traditional regexp is along these lines:

    
    
    pattern = (
        "(?:"
        r"\d+(?:\.\d+)(:?[Ee][-+]?\d+)"
        "|"
        r"\.\d+(:?[Ee][+-]?\d+)"
        ")"
    )
    

But you can always do things the easy way:

    
    
    def is_number(x):
        try:
            float(x)
            return True
        except ValueError:
            return False
    

