On 9/25/2026 3:19 PM, Stefan Ram wrote:
[email protected] (Stefan Ram) wrote or quoted:
Johann 'Myrkraverk' Oskarsson <[email protected]> wrote or quoted:
What is a good way to combine regular expressions in Python?  We are
cogitating the most /Pythonic/ way to make this happen.
    number:
        sign? integer-constant
        | sign? floating-point-constant
    integer-constant:
        digit-sequence
    floating-point-constant:
        fractional-constant exponent?
        | digit-sequence exponent
    fractional-constant:
        digit-sequence? "." digit-sequence
        | digit-sequence "."
    exponent:
        ( "e" | "E" ) sign? digit-sequence
    sign:
        "+" | "-"
    digit-sequence:
        digit
        | digit digit-sequence
    digit:
        "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
Maybe something like this?

   We can also write the definitions in the same order as in the EBNF.

import re
from typing import Final

NUMBER = lambda: 
rf"^{SIGN()}?(?:{INTEGER_CONSTANT()}|{FLOATING_POINT_CONSTANT()})$"

INTEGER_CONSTANT = lambda: DIGIT_SEQUENCE()

FLOATING_POINT_CONSTANT = lambda: \
rf"(?:{FRACTIONAL_CONSTANT()}(?:{EXPONENT()})?|{DIGIT_SEQUENCE()}{EXPONENT()})"

FRACTIONAL_CONSTANT = lambda: \
rf"(?:(?:{DIGIT_SEQUENCE()})?\.{DIGIT_SEQUENCE()}|{DIGIT_SEQUENCE()}\.)"

EXPONENT = lambda: rf"[eE]{SIGN()}?{DIGIT_SEQUENCE()}"

SIGN = lambda: r"[+-]"

DIGIT_SEQUENCE = lambda: rf"{DIGIT()}+"

DIGIT = lambda: r"[0-9]"

NUMBER_VALIDATOR: Final[ re.Pattern[ str ]] = re.compile( NUMBER() )

example = "123"
is_ok = bool( NUMBER_VALIDATOR.match( example ))
print( is_ok )

Newsgroups: comp.lang.python,alt.folklore.computers
Followup-To: comp.lang.python

What is the reason for using a lambda instead of a string? E.g., I usually write

DIGITre = "[0-9]"
DIGIT = re.compile(DIGITre)

--
https://mail.python.org/mailman3//lists/python-list.python.org

Reply via email to