Charles Lambert
Charles Lambert

Reputation: 5132

How do I find multiple non-greedy instances of a Regex?

I have the following text

var s = "{{http://foo.com:::Foo Inc.}} would like you to visit {{http://foo.com/home:::Our New Home Page}}"

I want to parse out both instances of the double braces using the following Regex and MatchEvaluator

var r = new Regex("\\{\\{(.+)\\:\\:\\:(.+)\\}\\}");

public string Convert(Match m) {
  var link = m.Groups[0].ToString();
  var text = m.Groups[1].ToString();
  return "<a href=\"" + link + "\">" + text + "</a>";
}

so that the output would be:

var output = r.Replace(s, Convert);
// output = "<a href="http://foo.com">Foo Inc.</a> would like you to visit <a href="http://foo.com/home">Our New Home Page</a>"

It keeps matching the whole string instead of each set of brackets. How can I get this to do non-greedy matches?

I have tried wrapping it in ()? but that does not produce a non-greedy match

Upvotes: 1

Views: 116

Answers (1)

anubhava
anubhava

Reputation: 785156

Try this non-greedy, negation based regex:

var r = new Regex( "\\{\\{(.+?):{3}([^}]+)\\}\\}" );

RegEx Demo

Upvotes: 2

Related Questions