简体   繁体   English

嵌套括号的正则表达式或字符串解析

[英]Regular expression or string parsing for nested brackets

Consider the following string as input. 考虑以下字符串作为输入。 The second & third AND are redundant. 第二和第三个AND是多余的。 I want to removed it. 我要删除它。

Input 输入

 AND(AND(string("test message")),filter(AND(OR(source:string("XYZ"),source:string("ABC")))))

I want the output as 我希望输出为

 AND(string("test message"),filter(OR(source:string("XYZ"),source:string("ABC"))))

Basically the input string has AND operator used, but there is only one argument specified, this makes the input a invalid string. 基本上,输入字符串使用了AND运算符,但是仅指定了一个参数,这使输入成为无效字符串。 I want to modify the string to remove AND such that it has only one argument specified in it. 我想修改字符串以删除AND,这样它只有一个自变量。

What should be the best approach. 什么是最好的方法。 Regular expression or string parsing. 正则表达式或字符串解析。 My string can be very long. 我的弦可能很长。

I checked multiple posts & seems like regular expression is not recommended especially if it is too much nested. 我检查了多个帖子,似乎不建议使用正则表达式,特别是如果嵌套太多的话。

Please suggest the best way to handle this case. 请提出处理这种情况的最佳方法。

Some input & their output 一些输入及其输出

1. AND(string(""test message"")) 1. AND(string(“” test message“”))

string(""test message"")
  1. AND(AND(string(""test message"")),filter(AND(OR(source:string(""XYZ""),source:string(""ABC""))))) AND(AND(string(“(”“ test message”“))),filter(AND(OR(source:string(”“ XYZ”“),source:string(”“ ABC”“)))))))

    AND(string(""test message""),filter(OR(source:string(""XYZ""),source:string(""ABC"")))) AND(string(“” test message“”),filter(OR(source:string(“” XYZ“”),source:string(“” ABC“”)))))

  2. AND(string(""test message""),filter(OR(source:string(""XYZ""),source:string(""ABC"")))) AND(string(""test message""),filter(OR(source:string(""XYZ""),source:string(""ABC"")))) AND(string(“” test message“”),filter(OR(source:string(“” XYZ“”),source:string(“” ABC“”))))))AND(string(“” test message“” ),过滤器(OR(来源:字符串( “” XYZ “”),来源:字符串( “” ABC “”))))

Annu Annu

If you go the regex route then a positive lookahead followed by a negative lookahead could work: 如果您使用正则表达式,则可以先进行正向先行再进行负向先行:

string result = Regex.Replace(searchText, "(?i)(?x)(?(?<!AND\\()AND\\()|(?(?=\\){2})(?!\\){3})\\))", "");

Input: 输入:

AND(AND(string("test message")),filter(AND(OR(source:string("XYZ"),source:string("ABC")))))

AND(string(""test message""))

AND(string(""test message""),filter(OR(source:string(""XYZ""),source:string(""ABC"")))) 

Result: 结果:

AND(string("test message"),filter(OR(source:string("XYZ"),source:string("ABC"))))

string(""test message"")

string(""test message""),filter(OR(source:string(""XYZ""),source:string(""ABC""))) 
I tried it in tcl , this is the soultion

regsub -all {\(AND} $string "" string .u will get the expected output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM