簡體   English   中英

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

[英]What is the best way to parse strings and nested brackets in 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 不起作用,但我還沒有找到新的解決方案。 有什么辦法可以做到這一點嗎?

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

(?:[^(){}]+|(?:(?:(?'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();
}

output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM