user2739143
user2739143

Reputation: 621

Extracting a Floating point exponential formatted number from a text file

I'm trying to extract a floating point exponential number from a number of .txt files that is searched for using a phrase and then extracted. For example I have a .txt file that looks like this.

FEA Results:
Tip rotation (deg) =, 7.107927E-18
Tip displacement =, 3.997556E-07

And I'm extracting the tip rotation data using the following script:

regexp = re.compile(r'Tip rotation .*?([0-9.-]+)')
    with open(fileName) as f:
        for line in f:
            match = regexp.match(line)
            if match:
                rotations.append(float((match.group(1))))

The problem is it only returns the first part of the floating point exponential (i.e. 7.107927 instead of 7.107927E-18). Any idea on how I could correct it?

Upvotes: 1

Views: 675

Answers (2)

John Zwinck
John Zwinck

Reputation: 249502

Your regex has this:

([0-9.-]+)

It's missing the E - add that in the brackets (at the front or the back, doesn't matter). Also, you may need to move the minus sign to the front, so it isn't interpreted as a range. Like this:

([-0-9.E]+)

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328760

Your regular expression doesn't allow for E-18. Specifically, E isn't mentioned.

See this question for better regexps: How to detect a floating point number using a regular expression

Upvotes: 0

Related Questions