问题
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.
回答1:
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}
$
来源:https://stackoverflow.com/questions/17933119/java-regular-expression-where-each-character-occurs-0-1-times