2012-07-26 17 views
2

我有正則表達式:(?ms)(?<attribute>\[.+?\]|public|private|\s)+?class爲什麼下面的正則表達式匹配這個文本?

和我有文字:

[attribute] 
public int a; 

[attribute C] 
[attribute B] 
public class Test{ 

} 

我想知道爲什麼我張貼匹配的正則表達式:

[attribute] 
public int a; 

[attribute C] 
[attribute B] 
public class 

我想它應該符合:

[attribute C] 
[attribute B] 
public class 

糾正我,如果我錯了。我認爲正則表達式應該被讀取的方式是:

查找屬性([某些屬性])或公共關鍵字或私有關鍵字或空間。

所以首先,正則表達式引擎應該匹配[屬性],然後是'\ n'(換行),然後是public關鍵字。在這之後,關鍵字int不是一個選項,爲什麼它匹配它?

+0

我強烈建議RegexBuddy,如果你還沒有它。我不以任何方式附屬於產品;我就喜歡。 – Odrade 2012-07-26 02:02:33

回答

3

的問題是,您所使用的匹配任何一個點,包括關閉方括號,空格,以及(在單行模式)換行符:

\[.+?\] 

你應該使用這樣的:

\[[^\]]+\] 

說明:

 
\[  Match a literal open square bracket. 
[^\]] Match any character except a close square bracket. 
+  One or more. 
\]  Match a literal close square bracket. 
+0

是啊,但我使其不貪的意義,這將繼續下去,直到它匹配「]」我想......爲什麼會匹配'公衆詮釋一個;'我仍然困惑笑。 +1使其起作用 – 2012-07-26 00:27:19

+0

無論匹配成功還是失敗,貪婪都不會改變。它只會改變搜索順序。 – 2012-07-26 00:28:12

+0

非常感謝。我會盡快堆棧溢出讓我 – 2012-07-26 00:31:34

1

使用此Regex

((?<attribute>(?:public|private|\[[^\]]+\]))[\r\n\s]+)*class 

,並給予命名組attribute。你的代碼可以是這樣的:

foreach (Match match in Regex.Matches(inputString, @"((?<attribute>(?:public|private|\[[^\]]+\]))[\r\n\s]+)*class")) 
{ 
    var attributes = new List<string>(); 
    foreach (Capture capture in match.Groups["attribute"].Captures) 
    { 
     attributes.Add(capture.Value); 
    } 
} 
+0

這可行,但你沒有給出有關OP的正則表達式原始問題的任何解釋。 – Odrade 2012-07-26 02:01:32

相關問題