I want to write a regex expression for words with even-numbered length.
For example, the output I want from the list containing the words:
{"blue", "ah", "sky", "wow", "neat"}
is {"blue", "ah", "neat}
.
I know that the expression w{2}
or w{4}
would produce 2-worded or 4-worded words, but what I want is something that could work for all even numbers. I tried using w{%2==0}
but it doesn’t work.
Advertisement
Answer
You can repeat 2 word characters as a group between anchors ^
to assert the start and $
to assert the end of the string, or between word boundaries b
^(?:w{2})+$
See a regex demo.
import re strings = [ "blue", "ah", "sky", "wow", "neat" ] for s in strings: m = re.match(r"(?:w{2})+$", s) if m: print(m.group())
Output
blue ah neat