[英]regex for removing curly brackets with nested curly brackets
This is my string: "This Is {{ dsfdf {{dsfsd}} ewrwrewr }} My Result"
. 这是我的字符串:
"This Is {{ dsfdf {{dsfsd}} ewrwrewr }} My Result"
。
I want to remove the outer curly brackets with their content. 我想删除外部花括号及其内容。 The result should be
"This Is My Result"
. 结果应该是
"This Is My Result"
。
This is my best shot at the moment: 这是我目前最好的镜头:
Text = Regex.Replace(Text, "{{([^}]*)}}", String.Empty);
but it doesn't work well. 但效果不佳。 I get
"This Is ewrwrewr }} My Text"
我收到
"This Is ewrwrewr }} My Text"
Perhaps it should be solved with Balance Matching... 也许应该用余额匹配解决...
I would be very appreciate if someone could help me solve it, because although many tries I couldn't do it myself. 我会很感激,如果有人可以帮助我解决这个问题,因为虽然多次尝试我不能做我自己。
A simple but slow way is to apply the regex multiple times until there are no more changes: 一种简单但缓慢的方法是多次应用正则表达式,直到没有更多更改为止:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string s = "This Is {{ dsfdf {{dsfsd}} ewrwrewr }} My Result";
Regex regex = new Regex("{{({?}?[^{}])*}}");
int length;
do
{
length = s.Length;
s = regex.Replace(s, "");
} while (s.Length != length);
Console.WriteLine(s);
}
}
What do You think about: 你有什么想法:
string test = "This Is {{ dsfdf {{dsfsd}} \n jkhhjk ewrwrewr }} My Result";
Console.WriteLine(Regex.Replace(test, "{{.*}}", String.Empty, RegexOptions.Singleline));
Version without "Regex": 没有“ Regex”的版本:
string test = "This Is {{ dsfdf {{dsfsd}} \n jkhhjk ewrwrewr }} My Result";
int startIndex = test.IndexOf("{");
int length = test.LastIndexOf("}") - startIndex + 1;
Console.WriteLine(test.Replace(test.Substring(startIndex, length), String.Empty));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.