首页 > 解决方案 > 在 C# 中解析字符串和嵌套括号的最佳方法是什么?

问题描述

我正在尝试编写一个程序,该程序采用带引号和嵌套括号的常规字符串并将它们分解为列表。

到目前为止,我正在使用这个 RegEX :@"[\""].+?[\""]|\{.*\}|(?=\()(?:(?=.*?\((?!.*?\1)(.*\)(?!.*\2).*))(?=.*?\)(?!.*?\2)(.*)).)+?.*?(?=\1)[^(]*(?=\2$)|[^ ]+"

我想要它做的是: if (eval (date day) == "14") {print "Today is the 14th"} else {print "It is not the 14th"}

if
(eval (date day) == "14")
{print "Today is the 14th"}
else
{print "It is not the 14th"}

但它返回为

if
(eval (date day) == "14")
{print "Today is the 14th"} else {print "It is not the 14th"}

我在括号中遇到了这个问题,并在网上找到了解决方案,但是当我尝试将其更改为与 {} 一起使用时,它不起作用。

我在网上读到 RegEX 不起作用,但我还没有找到新的解决方案。有什么办法可以做到这一点吗?

标签: c#regex

解决方案


如果分隔符是 () 和 {},并且您想忽略可能包含
分隔符的字符串内容,您只需要使用平衡的文本正则表达式。

(?:[^(){}]+|(?:(?:(?'opP'\()(?>[^()"]+|"[^"]*")*)+(?:(?'clP-opP'\))(?>[^()"]+|"[^"]*")*?)+)+(?(opP)(?!))|(?:(?:(?'opBr'\{)(?>[^{}"]+|"[^"]*")*)+(?:(?'clBr-opBr'\})(?>[^{}"]+|"[^"]*")*?)+)+(?(opBr)(?!)))

C# 示例

Regex RxParts = new Regex(@"(?:[^(){}]+|(?:(?:(?'opP'\()(?>[^()""]+|""[^""]*"")*)+(?:(?'clP-opP'\))(?>[^()""]+|""[^""]*"")*?)+)+(?(opP)(?!))|(?:(?:(?'opBr'\{)(?>[^{}""]+|""[^""]*"")*)+(?:(?'clBr-opBr'\})(?>[^{}""]+|""[^""]*"")*?)+)+(?(opBr)(?!)))" );
string test_sample = @"if (eval (date day) == ""14"") {print ""Today is the 14th""} else {print ""It is not the 14th""}";

Match M = RxParts.Match(test_sample);
while ( M.Success )
{
    string strM = M.Value.Trim();
    if ( strM.Length > 0 )
        Console.WriteLine("{0}", strM);
    M = M.NextMatch();
}

输出

if
(eval (date day) == "14")
{print "Today is the 14th"}
else
{print "It is not the 14th"}

推荐阅读