Problem:
Match words in which each char of the regular expression occurs once at most.
The word must be of a certain size, let's say "{2,5}"
One specific char must be in the word, let's say char "e"
What I've got:
word.matches("^[abcde]{2,5}$");
This matches all words where the chars a, b, c, d, and e occur 0..5 times. Therefore the words "abba" and "dead" are matched even though "abba" uses the char "b" two times and "dead" uses the char "d" two times. The expression also ignores if the char "e" is in the word.
What I want is a match where each character is used once maximum, the word is 2-5 letters long and the char "e" is in the word. A legit match would then be "bead" for instance since each char is used once max and the char "e" is in the word.
You could use expressions like:
^(?=[abcd]*e)(?:([abcde])(?![abcde]*?\1)){2,5}$
Some comments:
^
(?=[abcd]*e) # make sure there is an "e"
(?:
([abcde]) # match a character and capture it
(?! # make sure it's not repeated
[abcde]*?
\1 # reference to the previously matched char
)
){2,5}
$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With