Last active
May 10, 2020 08:01
-
-
Save smac89/bfefc0303c2aab6cac0b08055e195c55 to your computer and use it in GitHub Desktop.
Floating point regex: A regular expression to match any valid python floating point value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf8 | |
# the above tag defines encoding for this document and is for Python 2.x compatibility | |
# See it in action https://regex101.com/r/ObowxD/5 | |
import re | |
regex = r""" | |
(?xm) | |
(?:\s|^) | |
([-+]*(?:\d+\.\d*|\.?\d+)(?:[eE][-+]?\d+)?) | |
(?=\s|$) | |
""" | |
test_str = ("0.2 2.1 3.1 ab 3 c abc23\n" | |
"4534.34534345\n" | |
".456456\n" | |
"1.\n" | |
"1e545\n" | |
"1.1e435ff\n" | |
".1e232\n" | |
"1.e343\n" | |
"1231ggg\n" | |
"112E+12\n" | |
"4\n" | |
"5545ggg\n" | |
"dfgdf.5444\n" | |
"12312.1231\n" | |
".1231\n" | |
"1231\n" | |
"1.wrr\n" | |
"1 34345 234 -121\n" | |
"177\n" | |
"-1e+ -1e+0 1e-1") | |
matches = re.finditer(regex, test_str) | |
for matchNum, match in enumerate(matches): | |
matchNum = matchNum + 1 | |
print ("Match {matchNum} was found at {start}-{end}: {match}".format( | |
matchNum=matchNum, | |
start=match.start(), | |
end=match.end(), | |
match=repr(match.group()))) | |
for groupNum in range(0, len(match.groups())): | |
groupNum = groupNum + 1 | |
print ("\tGroup {groupNum} found at {start}-{end}: {group}".format( | |
groupNum=groupNum, start=match.start(groupNum), end=match.end(groupNum), | |
group=match.group(groupNum))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment