2012-04-18 53 views
1

我尋找一個正則表達式的字符串包含「一」和「b」,它具有以下兩個屬性搜索字符串: 1:字符串有偶數個字符 2:字符串可能不包含「AA」具體情況

+2

這幾乎是不可能做到這一點與一個正則表達式。 – kirilloid 2012-04-18 09:26:08

+0

你應該可以用3個正則表達式來做到這一點。每個條件一個:P – ArjunShankar 2012-04-18 09:38:54

+0

字符串只包含'a'和'b'還是'abcd'是一個有效的字符串? – Toto 2012-04-18 09:54:38

回答

0

它可與Perl兼容的正則表達式可以輕鬆完成: ^(ab|bb|(ba(?!a)))*$

基本上它說,字符串必須由abbbba子以任意順序混合,但ba不能按照其他a字符。

由於所有這些子表達式的長度都是偶數,所以字符串的長度將會更長。 aa不能出現在一個字符串中,因爲它出現的唯一方法是在子字符串baab中,但正則表達式特別限制ba後面跟着a

1

這是可能的標準(舊)的正則表達式:

(ab|bb|(ba)*bb)*(ba)*

1

如何:

/(?=^(?:..)+$)(?!aa)(?=.*a)(?=.*b)/ 

解釋:

/   : delimiter 
      : control there are an even number of char 
    (?=  : positive lookahead 
    ^ : begining of string 
    (?: : non capture group 
     .. : 2 characters 
    )+ : one or more times 
    $  : end of string 
) 
      : control there aren't aa 
    (?!  : negative look ahead 
    aa : aa 
) 
      : control there is at least an a 
    (?=  : positive lookahead 
    .*a : at least an a 
) 
      : control there is at least a b 
    (?=  : positive lookahead 
    .*b : at least a b 
) 
/  : delimiter