我想為偶數長度的單詞撰寫一個正則運算式。
例如,我想要從包含單詞的串列中輸出:
{"blue", "ah", "sky", "wow", "neat"}是{"blue", "ah", "neat}.
我知道運算式\w{2}or\w{4}會產生 2 字或 4 字的單詞,但我想要的是可以適用于所有偶數的東西。我嘗試使用\w{%2==0}但它不起作用。
uj5u.com熱心網友回復:
您可以在錨點之間重復 2 個單詞字符作為一組,以斷言字串^的開頭和$結尾,或在單詞邊界之間重復\b
^(?:\w{2}) $
查看正則運算式演示。
import re
strings = [
"blue",
"ah",
"sky",
"wow",
"neat"
]
for s in strings:
m = re.match(r"(?:\w{2}) $", s)
if m:
print(m.group())
輸出
blue
ah
neat
uj5u.com熱心網友回復:
如果您不需要對集合中的字串進行額外驗證,您可以簡單地使用
words = {"blue", "ah", "sky", "wow", "neat"}
print( list(w for w in words if len(w) % 2 == 0) )
# => ['ah', 'blue', 'neat']
請參閱此 Python 演示。
如果您想確保回傳的單詞是由字母組成的,您可以使用
import re
words = {"blue", "ah", "sky", "wow", "neat"}
rx = re.compile(r'(?:[^\W\d_]{2}) ') # For any Unicode letter words
# rx = re.compile(r'(?:[a-zA-Z]{2}) ') # For ASCII only letter words
print( [w for w in words if rx.fullmatch(w)] )
# => ['blue', 'ah', 'neat']
請參閱此 Python 演示。一個(?:[^\W\d_]{2}) 模式匹配任何兩個 Unicode 字母的一個或多個出現。與 一起re.fullmatch,它要求字串由偶數個字母組成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420838.html
標籤:
