2008-09-25 41 views
1

如何反轉.NET正則表達式匹配?我只想提取匹配的文本,例如我想從HTML文件中提取所有IMG標籤,但只提取圖片標籤。反轉正則表達式匹配

回答

2

這與倒置正則表達式無關。只需搜索相關的文本並將其放入一個組中即可。

1

我與大衛H:倒置意味着你不要想要匹配,而是圍繞比賽的文本,在這種情況下正則表達式方法Split()將工作。這就是我的意思:

static void Main(string[] args) 
{ 
    Regex re = new Regex(@"\sthe\s", RegexOptions.IgnoreCase); 

    string text = "this is the text that the regex will use to process the answer"; 

    MatchCollection matches = re.Matches(text); 
    foreach(Match m in matches) 
    { 
     Console.Write(m); 
     Console.Write("\t"); 
    } 

    Console.WriteLine(); 

    string[] split = re.Split(text); 
    foreach (string s in split) 
    { 
     Console.Write(s); 
     Console.Write("\t"); 
    } 
}