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

坚强是说给别人听的谎言 提交于 2019-12-10 14:06:45

问题


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.


回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!