2012-07-19 51 views
1

爲什麼我的比賽成功等於假?我已經在Regexbuddy中測試了下面的模式和輸入,並且它是成功的。爲什麼我的比賽成功是假?

string pattern = @"(?i)(<!-- START -->)(.*?)(?i)(<!-- END -->)"; 
string input = @"Hello 
    <!-- START --> 
    is there anyone out there? 
    <!-- END -->"; 

Match match = Regex.Match(input, pattern, RegexOptions.Multiline); 
if (match.Success) //-- FALSE! 
{ 
    string found = match.Groups[1].Value; 
    Console.WriteLine(found); 
} 

enter image description here

+0

你確定.NET接受這種情況忽略的語法嗎? – 2012-07-19 05:21:16

+0

@Chico:剛剛測試過。是。 – 2012-07-19 05:29:13

+1

第一個'(?i)'在它不區分大小寫後做成所有事情,所以第二個沒有做任何有用的事情。如果你想限制它的效果,你可以使用這種形式:'(?i:<! - START - >)'。在這種情況下不需要,因爲'START'和'END'是它唯一影響的東西。 – 2012-07-19 05:45:28

回答

2

使用s選項強制您的匹配模式.包括\r任何字符嘗試了這一點

string pattern = @"(?is)(<!-- START -->)(.*?)(<!-- END -->)"; 
string input = @"Hello 
    <!-- START --> 
    is there anyone out there? 
    <!-- END -->"; 

Match match = Regex.Match(input, pattern, RegexOptions.None); 
if (match.Success) //-- FALSE! 
{ 
    string found = match.Groups[1].Value; 
    Console.WriteLine(found); 
} 

\n

0

使用單行選項

Regex RegexObj = new Regex("(?i)(<!-- START -->)(.*?)(?i)(<!-- END -->)", 
     RegexOptions.Singleline);