smac89
11/28/2016 - 7:50 PM

Floating point regex: A regular expression to match any valid python floating point value. See it in action https://regex101.com/r/ObowxD/5

Floating point regex: A regular expression to match any valid python floating point value. See it in action https://regex101.com/r/ObowxD/5

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

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)))