正则表达式在花括号之间获取字符串

时间:2011-03-17 09:27:45

标签: c# regex

我想问一下C#中的正则表达式。

我有一个字符串。例如:" {欢迎来到{stackoverflow}。这是一个问题C#}"

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

感谢前进,对不起我的英语。

3 个答案:

答案 0 :(得分: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);
        }
    }

}

答案 1 :(得分:0)

ve written a little RegEx, but haven测试了它,但您可以尝试这样的事情:

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

......并建立起来。

答案 2 :(得分:0)

谢谢大家。我有解决方案。我用堆栈代替正则表达式。我已经按“{”进行堆叠,当我遇到“}”时,我会弹出“{”并获得索引。我从该索引获取字符串索引“}”。再次感谢。