如何指定仅匹配首次出现? [英] How to specify to only match first occurrence?

查看:53
本文介绍了如何指定仅匹配首次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I specify to only match the first occurrence of a regular expression in C# using Regex method?

这是一个例子:

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();

我希望只替换第一个< \ link> .然后对其余的这些匹配也做同样的事情.

I would like this to only replace up to the first <\link>. And then also do the same for the rest of these matches.

推荐答案

我相信您只需要在第一个示例上添加一个惰性限定符即可.每当通配符吃得太多"时,您要么在通配符上需要一个懒惰的限定符,要么在更复杂的情况下向前看.在顶部添加一个懒惰的限定符(.+?代替.+ ),您应该会很好.

I believe you just need to add a lazy qualifier on the first example. Whenever a wild card is "eating too much", you either need a lazy qualifier on the wild card or, in a more complicated scenario, look ahead. Add a lazy qualifier at the top (.+? in place of .+), and you should be good.

这篇关于如何指定仅匹配首次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆