Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解析C#中的字符串和嵌套括号的最佳方法是什么?_C#_Regex - Fatal编程技术网

解析C#中的字符串和嵌套括号的最佳方法是什么?

解析C#中的字符串和嵌套括号的最佳方法是什么?,c#,regex,C#,Regex,我正在尝试编写一个程序,该程序采用带引号和嵌套括号的常规字符串,并将它们分解为一个列表 到目前为止,我使用的是这个正则表达式:@“[\”“]”.+?[\”“].[\\\\\\\\\.[\\\\”(?:(?=...*?)((?!.*.\1)((?!.*.\1)((?!..\1)((?!.\2..*)(?!.\2)(*))+(?)(?=\1)[^(?=(?=\2$))[^++)+)(?)(?=\1)[^(?=(?=\2$)+)[^++) 我想让它做的是: if(eval(date day)=“14”

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

到目前为止,我使用的是这个正则表达式:
@“[\”“]”.+?[\”“].[\\\\\\\\\.[\\\\”(?:(?=...*?)((?!.*.\1)((?!.*.\1)((?!..\1)((?!.\2..*)(?!.\2)(*))+(?)(?=\1)[^(?=(?=\2$))[^++)+)(?)(?=\1)[^(?=(?=\2$)+)[^++)

我想让它做的是:
if(eval(date day)=“14”){print“今天是第14天”}否则{print“它不是第14天”}

但它的回报是

if
(eval (date day) == "14")
{print "Today is the 14th"} else {print "It is not the 14th"}
我对括号有这个问题,并在网上找到了一个解决方案,但当我试图将它改为使用{}时,它不起作用

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

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

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

输出

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

如果你有
if(eval(date day)=“14”){print“今天是第14个:)}怎么办?否则{print“它不是第14个:(:{{{}
?我不建议进行正则表达式解析。可能值得一看或一看。它们比正则表达式好得多,Superpower使用起来更好,pidgin更快。似乎可以编写自定义的解析器。计算开始括号和结束括号(并跟踪它们的索引),然后创建一组子字符串。但是,我不清楚如果这些特殊字符中有一个在字符串中,您要做什么。您是否忽略它?如果是,则有更多的理由自己滚动。输入的一致性如何?是否总是if..then..ELSE,或者每个块中是否有多个语句,no ELSE子句,等等,您将如何处理字符串列表?也许有一种方法可以实现您想要的,而不必首先创建此列表。
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"}