正则表达式:if,else if,els

2024-05-26 11:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python和正则表达式解析Gezel语言(http://rijndael.ece.vt.edu/gezel2/)的FSM语句

regex_cond = re.compile(r'.+((else\tif|else|if)).+')  
line2 = '@s0 else if (insreg==1) then (initx,PING,notend) -> sinitx;'
match = regex_cond.match(line2);

我很难区分如果else if。示例中的else if被识别为if。在


Tags: 语言httpifmatchelseregexedufsm
3条回答

您当前的问题是.+是贪婪的,因此它匹配@s0 else,而不是{}。要使其非贪心,请改用.+?

import re

regex_cond = re.compile(r'.+?(else\s+if|else|if).+')  
line2 = '@s0 else if (insreg==1) then (initx,PING,notend) -> sinitx;'
match = regex_cond.match(line2)
print(match.groups())
# ('else if',)

然而,正如其他人所建议的那样,使用Pyparsing这样的解析器比在这里使用re更好。在

不要这样做;请改用^{}。你以后会感谢你自己的。在


问题是.+是贪婪的,所以它正在吞噬{}。。。改为.+?。或者,不要,因为您现在使用的是pyparsing。在

regex_cond = re.compile( r'.+?(else\sif|else|if).+?' )
...
# else if

a\t与制表符匹配。第2行中的“else”和“if”之间没有制表符。您可以改为使用\s,它可以匹配任何空白字符。在

相关问题 更多 >