Python正则表达式-仅匹配包含A、B或C的单词
我可以使用什么正则表达式来匹配仅由字符A、B或C组成的单词?例如,正则表达式将捕捉abcbacbabbabcc和A、B和C,但不会捕捉ABCD、ABC1等。关于Python正则表达式-仅匹配包含A、B或C的单词,python,regex,match,Python,Regex,Match,我可以使用什么正则表达式来匹配仅由字符A、B或C组成的单词?例如,正则表达式将捕捉abcbacbabbabcc和A、B和C,但不会捕捉ABCD、ABC1等。关于\B[ABC]+\B呢?这样行吗 >>> regex = re.compile(r'\b[ABC]+\b') >>> regex.match('AACCD') #No match >>> regex.match('AACC') #match <_sre.SRE_Match
\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>
您要查找的正则表达式是
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)
>>> regex = re.compile(r'\b([ABC]+)\b', re.I)