2014-03-24 86 views
0

所有可能的匹配,比如我有以下字符串:獲取正則表達式

(hello(world)) program 

我想從一個字符串中提取以下幾個部分:

(hello(world)) 
(world) 

我一直在努力表達(\((.*)\))但我只得到(hello(world))

我怎樣才能做到這一點使用正則表達式

+1

我建議不要使用正則表達式這一點。對於不規則語言來說,這並不有用,尤其是涉及到嵌套時。 –

+0

我會建議你忽略上述(@VasiliSyrakis),因爲我們不知道「這是一個像方言一樣的LISP!」。遞歸(PERL REGEX FTW(不是perl本身!))會允許這樣做,他可能也想要最內部的匹配,所以'?:'可能是有用的。或者是一場不貪婪的比賽,沒有足夠的信息來制定他想要的。 –

+0

@VasiliSyrakis Hmm.me是一個新手,你能給出一個簡單的解釋,爲什麼正則表達式不是最好的選擇? –

回答

3

正則表達式可能不適合這個任務的最佳工具。您可能想要使用標記器。然而,這可以使用正則表達式,使用recursion來完成:

$str = "(hello(world)) program"; 
preg_match_all('/(\(([^()]|(?R))*\))/', $str, $matches); 
print_r($matches); 

說明:

(   # beginning of capture group 1 
    \(  # match a literal (
    (  # beginning of capture group 2 
    [^()] # any character that is not (or) 
    |  # OR 
    (?R) # recurse the entire pattern again 
)*  # end of capture group 2 - repeat zero or more times 
    \)  # match a literal) 
)   # end of group 1 

Demo

+0

Upvote for recursion,bit iffy on the answer,because we still still not WTF the OP want –

+2

上面的代碼返回**副本** ..您可以使用'$ new_arr = array_unique(call_user_func_array('array_merge',$ matches ));'擺脫重複。 @AmalMurali –

+0

@ShankarDamodaran:我想知道爲什麼這甚至是必要的? OP在哪裏說他希望重複刪除? –