非贪婪的正则表达式匹配

时间:2017-07-13 07:47:18

标签: regex regex-greedy

我想在此字符串中匹配if x > 64 then return 0, 0 end

 function if x > 64 then return 0, 0 end return 1, 0 end

我正在使用if(.*)then(.*)end。但是,这匹配:if x > 64 then return 0, 0 end return 1, 0 end,一个end太多了。

1 个答案:

答案 0 :(得分:0)

这应该做:

if(.*)then(.*?)end

您可以添加字词边界以确保将end匹配为单词,而不是变量名称的一部分:

if(.*)then(.*?)\bend\b

要分析代码,您可能应该使用解析器而不是正则表达式。