How to tell if one regular expression matches a subset of another regular expression?

前端 未结 7 2270
孤独总比滥情好
孤独总比滥情好 2020-12-01 14:23

I\'m just wondering if it\'s possible to use one regular expression to match another, that is some sort of:

[\'a-z\'].match([\'b-x\'])
True

[\'m-n\'].match(         


        
7条回答
  •  旧巷少年郎
    2020-12-01 15:18

    pip3 install https://github.com/leafstorm/lexington/archive/master.zip
    python3
    >>> from lexington.regex import Regex as R
    >>> from lexington.regex import Null
    >>> from functools import reduce
    >>> from string import ascii_lowercase, digits
    >>> a_z = reduce(lambda a, b: a | R(b), ascii_lowercase, Null)
    >>> b_x = reduce(lambda a, b: a | R(b), ascii_lowercase[1:-2], Null)
    >>> a_z | b_x == a_z
    True
    >>> m_n = R("m") | R("n")
    >>> zero_nine = reduce(lambda a, b: a | R(b), digits, Null)
    >>> m_n | zero_nine == m_n
    False
    

    Also tested successfully with Python 2. See also how to do it with a different library.

    Alternatively, pip3 install https://github.com/ferno/greenery/archive/master.zip and:

    from greenery.lego import parse as p
    a_z = p("[a-z]")
    b_x = p("[b-x]")
    assert a_z | b_x == a_z
    m_n = p("m|n")
    zero_nine = p("[0-9]")
    assert not m_n | zero_nine == m_n
    

提交回复
热议问题