开发者

How can I stop this regex from being greedy?

Currently this regex returns one match:

the best language in the world and the fastest language

How can I get it to return two matches:

the best language

the fastest language

string text = "C# is the best language in the world and the fastest language in the world";
string search = @"\bthe\b.*\blanguage\b&qu开发者_运维知识库ot;;
MatchCollection matches = Regex.Matches(text, search);
Console.WriteLine("{0} matches", matches.Count);
foreach (Match match in matches)
{
    Console.WriteLine("match '{0}' was found at index {1}", match.Value, match.Index);
}
Console.WriteLine("---");


Add ? after the *


Try this:

\bthe\b(?:(?!\bthe\b).)*\blanguage\b

It uses a negative lookahead assertion to require that "the" is not seen again between the matching "the" and "language".


this will match your requirement

/the (?:best|fastest) language/g
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜