简体   繁体   English

如何找到正则表达式的多个非贪婪实例?

[英]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 我想使用以下RegexMatchEvaluator解析双括号的两个实例

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 但这不会产生非贪婪的匹配

Try this non-greedy, negation based regex: 尝试以下基于非否定,否定的正则表达式:

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

RegEx Demo 正则演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM