2017-02-03 97 views
1

如果我想将一个字符串与As,Bs,Cs匹配,但是我的字符串不能包含多于一个1B和不多于4C的字符串?我会如何做到这一点,而不是很长时间?我有一个解决方案,在该解决方案中,我将字母B和Cs和A *的排列组合在一起。为包含至多一个字母的三个字母的字符串创建正则表达式?

正则表达式应该匹配的字符串,如:

AABCCCC

BAAACC

BAACACC

但不喜欢的东西:

AABB

BBBACCC

CACACACC

+0

显示输入的实施例和预期输出 – RomanPerekhrest

+0

在你的正则表达式的开始时,将两个负向前看符号:一个用于''([^ B] * B){2}'',一个用于'' ([^ C] * C){5}''。 – jasonharper

回答

2

你可以通过先行做到这一点:

如果,至少1B和C是必需的:

^(?=[^B]*B[^B]*$)(?=(?:[^C]*C[^C]*){1,4}$)[ABC]+$ 

否则:

^(?=[^B]*B?[^B]*$)(?=(?:[^C]*C[^C]*){0,4}$)[ABC]*$ 

说明:

^     : begining of line 
(?=     : lookahead, make sure we have: 
    [^B]*B[^B]*  : 0 or more non B arround one B 
    $    : until end of line 
)     : end lookahead 
(?=     : lookahead, make sure we have: 
    (?:    : start non capture group 
     [^C]*C[^C]* : 0 or more non C arround one C 
    ){1,4}   : 1 upto 4 times 
    $    : until end of line 
)     : end lookahead 
[ABC]+    : 1 or more any of these letters 
$     : end of line 
相关问题