2017-02-03 44 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 
相關問題