【问题标题】:Regular expression get string between curly braces正则表达式获取大括号之间的字符串
【发布时间】:2011-07-17 06:25:54
【问题描述】:

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

我有一个字符串。 ex : "{Welcome to {stackoverflow}. This is a question C#}"

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

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

【问题讨论】:

  • 您想将自己限制在只有两个级别的 {,还是无限级别?所以{{{{{{你好}}}}}}

标签: c# regex


【解决方案1】:

谢谢大家。我有解决办法。我使用堆栈而不是正则表达式。我已经将“{”推入堆栈,当我遇到“}”时,我将弹出“{”并获取索引。在我从该索引获取字符串到索引“}”之后。再次感谢。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      ive written a little RegEx, but havent 对其进行了测试,但您可以尝试以下方法:

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

      ...并以此为基础。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-29
        • 1970-01-01
        • 1970-01-01
        • 2015-07-05
        • 2013-07-20
        • 2018-07-30
        相关资源
        最近更新 更多