c# - 正则表达式获取花括号之间的字符串

标签 c# regex

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

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

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

感谢提前,抱歉我的英语不好。

最佳答案

Hi 不知道如何使用单个正则表达式来做到这一点,但添加一点递归会更容易:

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

}

关于c# - 正则表达式获取花括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5337166/

相关文章:

python - 使用正则表达式或常规 Python 进行字符串替换?

php - 在到达字符串中的第一个 p 标签之前删除每个 li 标签

PHP preg_split by new line with\R

javascript - 获取两个子字符串之间的字符串

c# - 自述文件包含在设置项目 VS2005 中时不显示其内容?

c# - 使用 groupby、sum 和 count 将 SQL 转换为 Linq

c# - 如何将数组的 JSON 数组作为单独的元素插入到 PostgreSQL 中

c# - 对 DTO 的 ASP.NET WebApi OData 支持

c# - 使用 C# 从 Web 应用程序打开文件夹,拒绝访问

python - 为什么 python 正则表达式中的 '\A' 在 [ ] 中不起作用?