簡體   English   中英

Python正則表達式 - 匹配僅包含A,B或C的單詞

[英]Python regex - Match words only containing A, B, or C

我可以使用什么正則表達式來匹配由字符A,B或C組成的單詞? 例如,正則表達式將捕獲ABCBACBACBABBABCC和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 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

您正在尋找的正則表達式是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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM