Regular expression to match all words ending with and containing three 'e's
I am trying t开发者_开发问答o write a regular expression that matches all words so that the only vowel is e and there are exactly three e's in the word, am writing this in python. I tried writing
(?= e){3}[^aiou]*
but it didn't work.
You want three e's, such that the stuff in between consists of non-vowels. You want a word, i.e. stuff that has a word boundary on either side.
Thus: a word boundary, zero or more non-vowels, an e, zero or more non-vowels, an e, zero or more non-vowels, an e, zero or more non-vowels, and a word boundary. But we can simplify that by grouping up the repeated pattern: a word boundary, three times: (zero or more non-vowels, an e), zero or more non-vowels, and a word boundary.
In regex-speak: \b(?:[^aeiou]*e){3}[^aeiou]*\b
.
You might be better off testing the two parts seperately.
First use:
^[^aiou]*$
Then use:
^([^e]*e[^e]*){3}$
\s[bcdfghjklmnpqrstvwxyz]*e[bcdfghjklmnpqrstvwxyz]*e[bcdfghjklmnpqrstvwxyz]*e[bcdfghjklmnpqrstvwxyz]*\s
http://rubular.com
If you are only working in ASCII, I would suggest this solution:
(?i)(?=^[^aiouy]*$)^(?:[^e]*e){3}[^e]*$
Here’s a demo of that pattern, randomly selecting ten matching words from the dict
list:
% perl -ne 'print if /(?i)(?=^[^aiouy]*$)^(?:[^e]*e){3}[^e]*$/' /usr/share/dict/words |
perl -e '@a = <>; print splice(@a, rand @a, 1) for 1..10'
centgener
geezer
sceptered
gentlemens
neckweed
whenceeer
tenderer
scentlessness
beswelter
entrenchment
Yes, my demo uses Perl, but the pattern should be just fine in Python as well. I’m just not so nimble whipping off one-liners in Python as I am in Perl. :)
精彩评论