I was reading some lines from a file, which I want to match to be floats, here is a minimal example:
import re
regex="[-+]?[0-9]+\.?[0-9]+([eE][-+]?[0-9]+)?"
string="0.00000000000000000E0 0.00000000000000000E0 0.00000000000000000E0"´
print(re.findall(regex,string))
, Which gives me
['E0', 'E0', 'E0']
Instead of the expected
['0.00000000000000000E0', '0.00000000000000000E0', '0.00000000000000000E0']
Change the regex to
regex=r"[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?"
^ ^^
The point is to use a non-capturing group instead of the capturing one so that findall did not have to return only the captured text (when there are no capturing groups defined in the pattern, re.findall will return whole matched texts).
Also, use a raw string literal always to define regex pattern to avoid any other misunderstanding.
A Python demo:
import re
regex=r"[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?"
string="0.00000000000000000E0 0.00000000000000000E0 0.00000000000000000E0"
print(re.findall(regex,string))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With