简体   繁体   English

正则表达式在 { } 之间匹配,但不是 {{ }}

[英]Regex to Match Between { } , but not {{ }}

I'm trying to match what's between 2 curly braces, but ignore scenarios with double/escape curly braces, ie "This is {match}, this is a {{non-match}}."我试图匹配两个大括号之间的内容,但忽略带有双/转义大括号的场景,即“这是{匹配},这是一个{{不匹配}}”。 which should just match "match".应该只匹配“匹配”。 I've tried:我试过了:

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

but it's too greedy但它太贪心了

You could take advantage of lookaheads/lookbehinds within a regular expression to match only content that occurs within a single set of curly braces with this expression:您可以利用正则表达式中的前瞻/后视来仅匹配使用此表达式的一组大括号中出现的内容:

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

There's probably a bit of room for optimization, but it should accomplish what you are looking to achieve.可能有一些优化空间,但它应该可以完成您想要实现的目标。

Explanation解释

// 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
}(?!})

Example例子

You can see an interactive example here and the related code demonstrated below which only returns the expected value from your single sets of quotes:您可以在此处查看交互式示例以及下面演示的相关代码,该代码仅从您的单组引号中返回预期值:

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

Would something like this be suitable?这样的东西合适吗?

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

It uses a negative lookbehind.它使用了负面的回顾。

This isn't complete, but it works for your example string.这并不完整,但它适用于您的示例字符串。 I'm not sure what you expect to happen in a situation where there are characters between the double curly braces.我不确定在双花括号之间有字符的情况下您期望发生什么。

eg: 'This is {fooo} asdfads {{bar} xxx }' or 'This is {foo} asdf { xx {bar}}'.例如:“这是 {fooo} asdfads {{bar} xxx }”或“这是 {foo} asdf { xx {bar}}”。

Be careful, the other answer posted (which is much better than mine btw) seems to pick up ' xx {bar' as a match to my second example.小心,发布的另一个答案(顺便说一句,比我的要好得多)似乎选择了 'xx {bar' 作为我的第二个示例的匹配项。

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

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