使用正则表达式解析IF条件

时间:2011-04-18 18:05:10

标签: regex

我需要创建RE符合以下IF条件

 string InputValue=" If (X.Value==” X”) then   X.Value = “X”;
    Elseif (X.Value==” X”) then X.Value = “X”;
    Elseif (X.Value==” Y ") then X.Value = “Y”;
    Elseif (X.Value== ” Z ")  then X.Value = “Z”;
    Else X.Value = “M”;";

因为你知道它只有1和0或许多ElseIF和0或1 Else,我也想考虑空间和Enter 我尝试使用以下RE,但失败了

    string pattern="If\([a-z]*\.Value==""[a-z]*""\) Then [a-z]*\.Value=""[a-z]*""\;
(ElseIf\([a-z]*\.Value==""[a-z]*""\) Then [a-z]*\.Value=""[a-z]*""\;)*
(Else [a-z]*\.Value=""[a-z]*""\;)?";

bool result = Regex.IsMatch(InputValue, pattern, RegexOptions.IgnoreCase);

欢迎所有想法

1 个答案:

答案 0 :(得分:0)

http://ideone.com/onS2e中一样:

string condition  = @"[_a-z]\w* \.VALUE \s* == \s* "" [^""]* """;
string assignment = @"[_a-z]\w* \.VALUE \s* =  \s* "" [^""]* "" \s* ;";
string pattern    = string.Format(
    @"\b     IF \s* \( \s* {0} \s* \) \s* THEN \s+ {1} \s*
    ( \b ELSEIF \s* \( \s* {0} \s* \) \s* THEN \s+ {1} \s* )*  # repeat ELSEIF any number of times
    ( \b ELSE                                  \s+ {1}     )?  # at most one ELSE",
    condition, assignment);

Regex myRegex = new Regex( pattern, RegexOptions.IgnorePatternWhitespace |
    RegexOptions.IgnoreCase | RegexOptions.Singleline );

更新:

http://ideone.com/1coOp中一样:

string pattern    = string.Format(
    @"^ \s*    IF \s* \( \s* {0} \s* \) \s* THEN \s+ {1} \s*
      ( \b ELSEIF \s* \( \s* {0} \s* \) \s* THEN \s+ {1} \s* )*  # repeat ELSEIF any number of times
      ( \b ELSE                                  \s+ {1}     )?  # at most one ELSE
        \s* $",
    condition, assignment);