【问题标题】:Python regex - Match words only containing A, B, or CPython regex - 匹配仅包含 A、B 或 C 的单词
【发布时间】:2013-05-15 01:16:00
【问题描述】:

我可以使用什么正则表达式来匹配仅由字符 A、B 或 C 组成的单词?例如,正则表达式会捕获 ABCBACBACBABBABCC 和 A 和 B 和 C,但不会捕获 ABCD、ABC1 等。

【问题讨论】:

    标签: python regex match


    【解决方案1】:

    \b[ABC]+\b 呢?这行得通吗?

    >>> regex = re.compile(r'\b[ABC]+\b')
    >>> regex.match('AACCD')  #No match
    >>> regex.match('AACC')   #match
    <_sre.SRE_Match object at 0x11bb578>
    >>> regex.match('A')      #match
    <_sre.SRE_Match object at 0x11bb5e0>
    

    \b 是一个单词边界。因此,在这里我们匹配任何单词边界,后跟只有 ABC 字符,直到下一个单词边界。


    对于那些不喜欢正则表达式的人,我们也可以在这里使用set 对象:

    >>> set("ABC").issuperset("ABCABCABC")
    True
    >>> set("ABC").issuperset("ABCABCABC1")
    False
    

    【讨论】:

      【解决方案2】:

      您要查找的正则表达式是r'\b([ABC]+)\b'

      你可以编译它:

      >>> regex = re.compile(r'\b([ABC]+)\b')
      

      然后你可以用它做一些事情:

      >>> regex.match('ABC') # find a match with whole string.
      >>> regex.search('find only the ABC') # find a match within the whole string.
      >>> regex.findall('this will find only the ABC elements in this ABC test text') # find 2 matches.
      

      如果要忽略大小写,请使用:

      >>> regex = re.compile(r'\b([ABC]+)\b', re.I)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-02
        相关资源
        最近更新 更多