This tool builds a regular expression for a numerical range.
pip install range-exUse range_regex for integer ranges and float_range_regex for decimal ranges.
range_regex matches only integers (including negatives). The range is inclusive on both ends.
from range_ex import range_regex
regex1 = range_regex(5, 89)
# (?:[5-9]|[2-7]\d|1\d|8\d)
regex2 = range_regex(-65, 12)
# (?:\-[1-9]|\-[2-5]\d|\-1\d|\-6[0-5]|\d|1[0-2])If you pass only one bound, the other is unbounded:
regex3 = range_regex(minimum=5)
# (?:[5-9]|[1-9]\d+)
regex4 = range_regex(maximum=89)
# (?:\-[1-9]\d*|\d|[2-7]\d|1\d|8\d)
regex5 = range_regex()
# (?:\-[1-9]\d*|[1-9]\d*|0)float_range_regex accepts int, float, Decimal, and decimal-parseable str bounds.
from range_ex import float_range_regex
regex6 = float_range_regex(0.5, 1.5, strict=True)
# (?:0?\.(?:[5-9]|[5-9]\d*)|1\.(?:(?:[0-5]|[0-4]\d*|50+))?|1\.)
regex7 = float_range_regex(0.5, 1.5, strict=False)
# (?:0?\.(?:[5-9]|[5-9]\d*)|1\.(?:(?:[0-5]|[0-4]\d*|50+))?|1\.?)
regex8 = float_range_regex(maximum="1.5", strict=True)
# (?:\-(?:(?:0|[1-9]\d*)\.\d+|(?:0|[1-9]\d*)\.|\.\d+)|0?\.\d+|0\.\d*|1\.(?:(?:[0-5]|[0-4]\d*|50+))?|(?:\-[1-9]\d*|[0-1])\.|\-0\.|\-0\.0+|\-\.0+)
regex9 = float_range_regex(strict=True)
# (?:\-?(?:0|[1-9]\d*)\.\d+|\-?(?:0|[1-9]\d*)\.|\-?\.\d+|(?:\-[1-9]\d*|[1-9]\d*|0)\.|\-0\.|\-0\.0+|\-\.0+)Both APIs support capturing=True to emit capturing groups ((...)) instead of non-capturing groups ((?:...)):
range_regex(-65, 12, capturing=True)
# (\-[1-9]|\-[2-5]\d|\-1\d|\-6[0-5]|\d|1[0-2])Note: Generated regexes can still match inside larger strings (for example, inside
abc25def). Use anchors like^...$if you need whole-string matches.
Contributions are very welcome. Please open an issue or a pull request if you have any suggestions or improvements.
To test your changes, run the following command:
pytest -n 5This project is based on regex_engine. Feel free to check it out.