简体   繁体   English

如何找到所有带有正则表达式的耦合支架?

[英]How to find all coupling bracket with regular expression?

I'd like to have one regular expression to find all curly brackets and replace them with other strings. 我想要一个正则表达式来查找所有大括号并将其替换为其他字符串。

For example, I want to replace " {foo} " with " FOO " and " {bar} " with " BAR " and " {} " with " EMPTY ". 例如,我想用“ FOO ”替换“ {foo} ”,用“ BAR ”替换“ { bar} ”,用“ EMPTY ”替换“ {} ”。 If the input is " abc {foo} def {bar} {} ", then the output is " abc FOO def BAR EMPTY ". 如果输入为“ abc {foo} def {bar} {} ”,则输出为“ abc FOO def BAR EMPTY ”。

Nested brackets or un-coupled brackets are not allowed. 不允许使用嵌套括号或非耦合括号。 If character "{" or "}" is necessary. 如果需要字符“ {”或“}”。 It should be doubled. 应该加倍。 So, "{{ def }}" is just "{ def }". 因此,“ {{def}}”仅仅是“ {def}”。

Other string in {} is not allowed. 不允许在{}中使用其他字符串。 Say, I just want " {foo} " and " {bar} ". 说,我只想要“ {foo} ”和“ {bar} ”。 So, " abc {xyz} def " should be recognized as invalid input. 因此,应将“ abc {xyz} def ”识别为无效输入。

If you have negative lookbehinds/lookaheads available: 如果您有否定的后顾之忧/前瞻功能:

(?<!{){([a-z]+)}(?!})

and replace with the value of the matching group. 并替换为匹配组的值。

The ([az]+) matches your contained character string, the (?<!{) makes sure there isn't a second { before your { , and the (?!}) makes sure there isn't a second } after your } . ([az]+)匹配您包含的字符串, (?<!{)确保在{之前没有第二个{ ,而(?!})确保在之后没有第二个}您的}

If you don't have lookbehinds/lookaheads, then 如果您没有后顾之忧,那么

(?^|[^{]){([a-z]+)}(?$|[^})

I would first go and replace {} with EMPTY without using a regular expression. 我首先要使用EMPTY替换{}而不使用正则表达式。

Then use 然后使用

(?<!{){(foo|bar)}(?!})

to match {foo} or {bar} but not {} or {{anything}} or {anything} 匹配{foo}{bar}但不匹配{foo} {}{{anything}}{anything}

Backreference no. 反向编号 1 contains the matched text. 1包含匹配的文本。

So a code snippet could look like 因此,代码段可能看起来像

Regex matches = new Regex(@"(?<!\{)\{(foo|bar)\}(?!\})", RegexOptions.IgnoreCase);
resultString = matches.Replace(subjectString, "$1".ToUpper());

(I hope that calling ToUpper() on a string works; I don't know C#, so please correct me if I'm wrong) (我希望在字符串上调用ToUpper()可以工作;我不知道C#,所以如果我错了,请纠正我)

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

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