正则表达式只进行最后一场比赛

时间:2018-03-06 16:05:14

标签: java regex

我为if / elif / else语句写了一个正则表达式  (\s|^)if\s*\((.*?)\)\s*then\s+do\s+(.*?)\s+end\n+(elif\s*\((.*?)\)\s*then\s+do\s+(.*?)\s+end\n+)*(else\s+then\s+do\s+(.*?)\s+end\n+)?但是当有2个或更多elif语句时,它只需要最后一个条件和语句

if (condition1) then do 
    Statement1
end
elif (condition2) then do
    Statement2
end
elif (condition3) then do 
    Statement3
end
else then do
    ElseStatement
end

输出:

Group 1.    0-0 
Group 2.    4-14    condition1
Group 3.    26-33   aagahd;
Group 4.    77-120  elif (condition3) then do Statement3 end
Group 5.    83-93   condition3
Group 6.    105-115 Statement3
Group 7.    120-144 else then do ElseStatement end
Group 8.    133-139 ElseStatement

我不知道为什么,但它没有定义第一个elif语句。怎么了?

P.S。我使用java

1 个答案:

答案 0 :(得分:-1)

星号需要进入群组,而不是外面。如果它在外面,则只有该组的最后一个匹配项存储在该组中。

请阅读此blog post,以获得我认为适用的更深入的解释。

相关问题