如何指定仅匹配第一次出现?

如何使用Regex方法指定仅匹配C#中第一次出现的正则表达式?

这是一个例子:

string text = @""; string pattern = @"()"; Regex myRegex = new Regex(pattern, RegexOptions.IgnoreCase); Match m = myRegex.Match(text); // m is the first match while (m.Success) { // Do something with m Console.Write(m.Value + "\n"); m = m.NextMatch(); // more matches } Console.Read(); 

我希望这只能替换第一个 。 然后对其余的比赛做同样的事情。

我相信你只需要在第一个例子中添加一个惰性限定符。 每当外卡“吃太多”时,你需要在外卡上使用懒惰的限定符,或者在更复杂的情况下,向前看。 在顶部添加一个惰性限定符( .+?代替.+ ),你应该很好。

Regex.Match(myString)返回它找到的第一个匹配项。

Match()对结果对象的后续调用NextMatch()将继续匹配下一个匹配项(如果有)。

例如:

  string text = "my string to match"; string pattern = @"(\w+)\s+"; Regex myRegex = new Regex(pattern, RegexOptions.IgnoreCase); Match m = myRegex.Match(text); // m is the first match while (m.Success) { // Do something with m m = m.NextMatch(); // more matches } 

编辑:如果您正在解析HTML,我会认真考虑使用HTML Agility Pack 。 你会为自己省去许多令人头疼的问题。

 string text = @""; string pattern = @"()"; //Regex myRegex = new Regex(pattern, RegexOptions.IgnoreCase); //Match m = myRegex.Match(text); // m is the first match Match m = Regex.Match(text, pattern, RegexOptions.IgnoreCase); /*while (m.Success) { // Do something with m Console.Write(m.Value + "\n"); m = m.NextMatch(); // more matches }*/ // use if statement; you only need 1st match if (m.Success) { // Do something with m.Value // m.Index indicates its starting location in text // m.Length is the length of m.Value // using m.Index and m.Length allows for easy string replacement and manipulation of text } Console.Read(); 

可能有点过于简化了,但如果你得到一组匹配并想要第一次出现,你可以查看Match.Index属性来找到最低的索引。

这是关于它的MSDN文档 。

如果它只是一个范围问题,那么我同意Rich的评论 – 你需要使用非贪婪的修饰语来阻止你的表达过度“吃”。

使用分组与RegExOptions.ExplicitCapture结合使用。

试试这个

 string text = @" "; string pattern = @"()"; Regex myRegex = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matches = myRegex.Matches(text); foreach (Match m in matches) { Console.Write(m.Value + "\n"); } Console.Read();