Skip to content Skip to sidebar Skip to footer

Regex To Match Scientific Notation

I'm trying to match numbers in scientific notation (regex from here): scinot = re.compile('[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)') re.findall(scinot, 'x = 1e4') ['1e4'] r

Solution 1:

Add anchor at the end of regex and alternative space or equal sign before the number:

[\s=]+([+-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+))$

Solution 2:

Simply add [^\w]? to exclude all alphanumeric characters that precede your first digit:

[+\-]?[^\w]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)

Technically, the \w will also exlude numeric characters, but that's fine because the rest of your regex will catch it.

If you want to be truly rigorous, you can replace \w with A-Za-z:

[+\-]?[^A-Za-z]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)

Another sneaky way is to simply add a space at the beginning of your regex - that will force all your matches to have to begin with whitespace.

Solution 3:

scinot = re.compile('[-+]?[\d]+\.?[\d]*[Ee](?:[-+]?[\d]+)?')

This regex would help you to find all the scientific notation in the text.

By the way, here is the link to the similar question: Extract scientific number from string

Post a Comment for "Regex To Match Scientific Notation"