[英]Java: Regular expression where each character occurs 0-1 times
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}" 这个词必须是一定的大小,让我们说“{2,5}”
One specific char must be in the word, let's say char "e" 一个特定的字符必须在单词中,让我们说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. 这匹配字符a,b,c,d和e出现0..5次的所有单词。 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.
因此,即使“abba”使用char“b”两次并且“dead”使用char“d”两次,单词“abba”和“dead”也匹配。 The expression also ignores if the char "e" is in the word.
如果字符中的字符“e”,表达式也会忽略。
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. 我想要的是一个匹配,每个字符最多使用一次,字长2-5个字母,字符“e”。 A legit match would then be "bead" for instance since each char is used once max and the char "e" is in the word.
例如,合法匹配将是“珠子”,因为每个char最多使用一次并且字符“char”。
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}
$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.