Lillem4n Lillem4n - 1 month ago 11
Java Question

Java: Regular expression where each character occurs 0-1 times

Problem:


  1. Match words in which each char of the regular expression occurs once at most.

  2. The word must be of a certain size, let's say "{2,5}"

  3. 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.

Answer Source

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}
$