开发者

Regular expression get string between curly braces

开发者 https://www.devze.com 2023-02-17 14:36 出处:网络
I want to ask about regular expression in C#. I have a string. ex : \"{Welcome to {stackoverflow}. This is a question C#}\"

I want to ask about regular expression in C#.

I have a string. ex : "{Welcome to {stackoverflow}. This is a question C#}"

Any idea about regular expressions to get content between {}. I want to g开发者_如何学JAVAet 2 string are : "Welcome to stackoverflow. This is a question C#" and "stackoverflow".

Thank for advance and sorry about my English.


Hi wouldn't know how to do that with a single regular expression, but it would be easier adding a little recursion:

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

}


ive written a little RegEx, but havent tested it, but you can try something like this:

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

...and build up on it.


Thanks everybody. I have the solution. I use stack instead regular expression. I have push "{" to stack and when I meet "}", i will pop "{" and get index. After I get string from that index to index "}". Thank again.

0

精彩评论

暂无评论...
验证码 换一张
取 消