2011-03-17 231 views
2

我想问一下C#中的正则表达式。正则表达式在大括号之间得到字符串

我有一个字符串。例如:{{欢迎使用{stackoverflow}}这是一个问题C#}“

关于正则表达式在{}之间获取内容的任何想法。我想得到2字符串是:“欢迎来到stackoverflow。这是一个问题C#”和“stackoverflow”。

感谢提前和对我的英语感到抱歉。

+0

你想限制自己只有两个{,或无限级别的水平?所以{{{{{{Hello}}}}}} – xanatos 2011-03-17 10:48:59

回答

0

谢谢大家。我有解决方案。我使用堆栈而不是正则表达式。我推动“{”堆栈,当我遇到“}”时,我会弹出“{”并获得索引。从该索引获得字符串到索引“}”后。再次感谢。

0

ve written a little RegEx, but haven牛逼测试,但你可以尝试这样的:

Regex reg = new Regex("{(.*{(.*)}.*)}"); 

...并建立起来就可以了。

1

嗨不知道怎么做,用一个正则表达式,但它会增加一点点递推简单:

using System; 
using System.Collections.Generic; 
using System.Text.RegularExpressions; 

static class Program { 

    static void Main() { 
     string test = "{Welcome to {stackoverflow}. This is a question C#}"; 
     // get whatever is not a '{' between braces, non greedy 
     Regex regex = new Regex("{([^{]*?)}", RegexOptions.Compiled); 
     // the contents found 
     List<string> contents = new List<string>(); 
     // flag to determine if we found matches 
     bool matchesFound = false; 
     // start finding innermost matches, and replace them with their 
     // content, removing braces 
     do { 
      matchesFound = false; 
      // replace with a MatchEvaluator that adds the content to our 
      // list. 
      test = regex.Replace(test, (match) => { 
       matchesFound = true; 
       var replacement = match.Groups[1].Value; 
       contents.Add(replacement); 
       return replacement; 
      }); 
     } while (matchesFound); 
     foreach (var content in contents) { 
      Console.WriteLine(content); 
     } 
    } 

} 
相关问题