2012-01-18 36 views
1

我使用以下正則表達式用於從所述表達找到組C#正則表達式 - 沒有得到外組

string pattern = @"(?<member>(?>\w+))\((?:(?<parameter>(?:(?>[^,()""']+)|""(?>[^\\""]+|\\"")*""|@""(?>[^""]+|"""")*""|'(?:[^']|\\')*'|\((?:(?<nest>\()|(?<-nest>\))|(?>[^()]+))*(?(nest)(?!))\))+)\s*(?(?=,),\s*|(?=\))))+\)"; 

string Exp = "GetValue(GetValue(GetValue(1 + 2) * GetValue(3 * 4))/GetValue(GetValue(5 * 6)/7)/8)"; 

我正在下列基團:

a)GetValue(GetValue(1 + 2)* GetValue(3 * 4))

b)GetValue(GetValue(5 * 6)/ 7)

我得到所有的組,但外組(GetValue(..../8))沒有得到?

模式中可能出現什麼問題?

+0

我試着創建一個正則表達式,但它什麼也沒有匹配:http://regexr.com?2voqv – 2012-01-18 14:01:04

+0

你能解釋一下預期的結果嗎?具體來說,你期望在每個組中捕獲什麼:member,parameter,nest,-nest。 – Grinn 2012-01-18 15:20:09

回答

0

因爲它是一個複雜的正則表達式,這將是很好的和實際的例子爲搜索字符串。在大多數情況下,我發現您需要進行貪婪的RegEx匹配。

例如:

Non-Greedy: 
"a.+?b": 

Greedy: 
"a.*b": 
0

如果你想有下面的比賽,這是不可能的正則表達式,獨自一人

  1. 的GetValue(的GetValue(的GetValue(1 + 2) *的GetValue(3 * 4))/的GetValue(的GetValue(5 * 6)/ 7)/ 8)
  2. 的GetValue(的GetValue(1 + 2)*的GetValue(3 * 4))
  3. 的GetValue(1 + 2 )
  4. 的GetValue(3 * 4)
  5. 的GetValue(的GetValue(5 * 6)/ 7)/ 8)
  6. 的GetValue(5 * 6)/ 7)

參見this article爲什麼。你可以,但是,使用遞歸來讓你的比賽中的比賽中,像(嚴重未經測試的僞代碼):

private List<string> getEmAll(string search) 
{ 
    var matches = (new Regex(@"Your Expression Here")).Match(search); 
    var ret = new List<string>(); 
    while (matches.Success) 
    { 
     ret.Add(matches.Value); 
     ret.AddRange(getEmAll(matches.Value)); 
     matches = matches.NextMatch(); 
    } 
    return ret; 
} 

... 

getEmAll("GetValue(GetValue(GetValue(1 + 2) * GetValue(3 * 4))/GetValue(GetValue(5 * 6)/7)/8)"); 

如果你想進一步分離出的匹配到匹配組,它會稍微複雜一些 - 但你得到了主旨。