Java:每个字符出现0-1次的正则表达式 [英] Java: Regular expression where each character occurs 0-1 times

查看:862
本文介绍了Java:每个字符出现0-1次的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

  1. 匹配单词,其中正则表达式的每个字符最多出现一次.

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

单词必须具有一定的大小,例如"{2,5}"

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

单词中必须有一个特定的char,例如char"e"

One specific char must be in the word, let's say char "e"

我所拥有的:

word.matches("^[abcde]{2,5}$");

这匹配字符a,b,c,d和e出现0..5次的所有单词.因此,即使"abba"两次使用字符"b",而"dead"两次使用字符"d",单词"abba"和"dead"也会匹配.该表达式还忽略了字符"e"是否在单词中.

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.

我想要的是一个匹配项,其中每个字符最多使用一次,该单词的长度为2-5个字母,并且单词中的字符为"e".合法的匹配将是"bead",例如,因为每个字符最大使用一次,并且字符"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. 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}$

一些评论:

^
(?=[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}
$

这篇关于Java:每个字符出现0-1次的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆