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

Jos*_*osh 26 c# regex

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

这是一个例子:

string text = @"<link href=""/_layouts/OracleBI/OracleBridge.ashx?RedirectURL=res/sk_oracle10/b_mozilla_4/common.css"" type=""text/css"" rel=""stylesheet""></link></link>";
string pattern = @"(<link).+(link>)";
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();
Run Code Online (Sandbox Code Playgroud)

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

wom*_*omp 33

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

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

例如:

  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
  }
Run Code Online (Sandbox Code Playgroud)


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


Ric*_*ich 33

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