2013-04-14 74 views
4

如何使一個正則表達式執行下列操作:如何在正則表達式中定義切換案例?

「一般來說,做一個通用的正則表達式,但如果特定字符相互關聯,請用不同的方式檢查這些特定字符後面的字符串」?

one == two && three | four 

一般正則表達式是:[&|=\s]+

這將導致分裂時:one, two, three, four

但如果我要申請不同的正則表達式,每次有一個=字符,並希望=後的表達來僅停止在|角色是什麼? 這樣我就可以得到結果:one, two && three, four

我該怎麼做?

+1

你的問題不完全清楚,(至少對我來說)。你是否在想這樣的事情:'[= 1 |] | [= 2 | = 3 |] | [= 4 |]' –

回答

7

這是一個可能性:

(?=[&|=\s])[&|\s]*(?:=[^|]*?[|][&|=\s]+)? 

或者在自由空間模式,並提供瞭解釋:

(?=[&|=\s]) # make sure there is at least a single separator character ahead; 
      # this is important, otherwise you would get empty matches, and 
      # depending on your implementation split every non-separator 
      # character apart. 
[&|\s]*  # same as before but leave out = 
(?:   # start a (non-capturing) group; it will be optional and treat the 
      # special =...| case 
    =   # match a literal = 
    [^|]*?  # match 0 or more non-| characters (as few as possible) 
    [|]  # match a literal | ... this is the same as \|, but this is more 
      # readable IMHO 
    [&|=\s]+ # and all following separator characters 
)?   # make the whole thing optional 

Try it out.

編輯:

我才意識到,這吞掉分ral part,但你也想回報一下。在這種情況下,您可能會更好地使用匹配而不是分割(使用find)。這種模式應該做的伎倆:

=[&|=\s]*([^|]+?)[&|=\s]*[|]|([^&|=\s]+) 

現在無論是第一個或第二個捕獲組將包含所需的結果。這裏有一個解釋:

#this consists of two alternatives, the first one is the special case 
    =   # match a literal = 
    [&|=\s]*  # consume more separator characters 
    ([^|]+?)  # match 1 or more non-| characters (as few as possible) and 
       # capture (group 1) 
    [&|=\s]*  # consume more separator characters 
    [|]   # match a literal | 
|    # OR 
    ([^&|=\s]+) # match 1 or more non-separator characters (as many as possible) 
       # and capture (group 2) 

Try it out.