2008-09-25 73 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"); 
    } 
}