我有一个正则表达式来查找单个 if-then-else 条件。
string pattern2 = @"if( *.*? *)then( *.*? *)(?:else( *.*? *))?endif";
现在,我需要扩展它并提供循环 if 条件。但是正则表达式不适合正确提取 then & else 部分。
示例循环 IF 条件:
if (2 > 1) then ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) else 1 endif
使用正则表达式的预期结果:
condition = (2>1) then part = ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) else part = 1
我可以检查 else & then 部分是否具有实际值或条件。然后我可以在此内部条件上使用相同的正则表达式,直到一切都得到解决。
当前正则表达式返回结果如下:
condition = (2 > 1) then part = ( if( 3>2) then ( if(4>3) then 3 else part = 3
意思是,它返回找到第一个“else”之后的值。但实际上,它必须从最后一个 else 中提取。
有人可以帮我解决这个问题吗?
最佳答案
您可以根据答案 Can regular expressions be used to match nested patterns? 调整解决方案(http://retkomma.wordpress.com/2007/10/30/nested-regular-expressions-explained/)。
该解决方案展示了如何在 html 标签之间匹配内容,即使它包含嵌套标签。对括号对应用相同的想法应该可以解决您的问题。
编辑:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String matchParenthesis = @"
(?# line 01) \((
(?# line 02) (?>
(?# line 03) \( (?<DEPTH>)
(?# line 04) |
(?# line 05) \) (?<-DEPTH>)
(?# line 06) |
(?# line 07) .?
(?# line 08) )*
(?# line 09) (?(DEPTH)(?!))
(?# line 10) )\)
";
//string source = "if (2 > 1) then ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) else 1 endif";
string source = "if (2 > 1) then 2 else ( if(3>2) then ( if(4>3) then 4 else 3 endif ) else 2 endif) endif";
string pattern = @"if\s*(?<condition>(?:[^(]*|" + matchParenthesis + @"))\s*";
pattern += @"then\s*(?<then_part>(?:[^(]*|" + matchParenthesis + @"))\s*";
pattern += @"else\s*(?<else_part>(?:[^(]*|" + matchParenthesis + @"))\s*endif";
Match match = Regex.Match(source, pattern,
RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
Console.WriteLine(match.Success.ToString());
Console.WriteLine("source: " + source );
Console.WriteLine("condition = " + match.Groups["condition"]);
Console.WriteLine("then part = " + match.Groups["then_part"]);
Console.WriteLine("else part = " + match.Groups["else_part"]);
}
}
}
关于c# - 正则表达式查找内部 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7596861/