c# - 在 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();
}
输出
if
(eval (date day) == "14")
{print "Today is the 14th"}
else
{print "It is not the 14th"}
推荐阅读
- python - 如何在python中使用带有范围函数的浮点变量?
- mysql - 如何在 ssp 简单类中使用 UNION ALL?
- r - rbindlist 的空间等价物?
- parsing - 使用输入图像中的特定区域通过 MS API 进行手写识别
- raku - 捕获和解析 Whatable 机器人的输出
- utf-8 - 将响应 cmd 解码为 utf-8
- java - 从测试启动一个弹簧启动应用程序
- angular - ng-select inside 对话框添加额外的隐藏高度
- ruby-on-rails - 弹性搜索+搜索
- css - 如何在 .angular-cli.json angular 5 中添加 css 媒体查询