【问题标题】:Regex to Match Between { } , but not {{ }}正则表达式匹配 { } ,但不匹配 {{ }}
【发布时间】:2019-12-18 04:04:20
【问题描述】:

我正在尝试匹配两个大括号之间的内容,但忽略带有双/转义大括号的场景,即“这是 {match},这是 {{non-match}}。”应该只匹配“匹配”。我试过了:

var regex = new Regex("{{1}(.*?)}{1}");

但是太贪心了

【问题讨论】:

  • 我稍后会调用类似 regex.Matches("This is {match}, this is a {{non-match}}.");

标签: c# .net regex


【解决方案1】:

这样的东西合适吗?

(?<!(^|){){[^}{]*}

它使用消极的后视。

这并不完整,但它适用于您的示例字符串。我不确定在双花括号之间有字符的情况下会发生什么。

例如:'This is {fooo} asdfads {{bar} xxx }' 或'This is {foo} asdf { xx {bar}}'。

请注意,发布的另一个答案(这比我的好得多)似乎选择了 'xx {bar' 作为我的第二个示例的匹配项。

【讨论】:

  • 这个解决方案表现最好
【解决方案2】:

您可以利用正则表达式中的lookaheads/lookbehinds 仅将出现在一组花括号中的内容与此表达式匹配:

(?<!{){([^{}]+)}(?!})

可能还有一点优化空间,但它应该可以实现您想要实现的目标。

说明

// This looks for an opening curly brace that isn't preceded by another one
(?<!{){
// This is your capturing group that matches one or more non-curly brace characters
([^{}]+)
// This looks for a closing curly brace that isn't followed by another
}(?!})

示例

您可以see an interactive example here 和下面演示的相关代码仅从您的单组引号中返回预期值:

var example = "This is a {match} but this {{is not a match}}.";

// Match only content from single gullwing braces
var matches = new System.Text.RegularExpressions.Regex(@"(?<!{){([^}{]+)}(?!})").Matches(example);

// Go through each match and output it
foreach(System.Text.RegularExpressions.Match match in matches)
{
    // You only want to grab the content within a given group
    Console.WriteLine(match.Groups[1].Value);
}

【讨论】:

  • 此解决方案也有效,但效果不如所选答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多