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
JavaScript
x
2
1
^(?:w{2})+$
2
See a regex demo.
JavaScript
1
15
15
1
import re
2
3
strings = [
4
"blue",
5
"ah",
6
"sky",
7
"wow",
8
"neat"
9
]
10
11
for s in strings:
12
m = re.match(r"(?:w{2})+$", s)
13
if m:
14
print(m.group())
15
Output
JavaScript
1
4
1
blue
2
ah
3
neat
4