繁体   English   中英

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

[英]Regular expression: if, else if, else

我正在尝试使用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被识别为if

\\ t匹配制表符。 第2行中的“ else”和“ if”之间似乎没有制表符。 您可以改用\\ s匹配任何空格字符。

不要这样 改用pyparsing 待会儿你会谢谢你的。


问题在于.+是贪婪的,所以在吃了else ......做.+? 代替。 还是不要,因为您现在正在使用pyparsing

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

您的直接问题是.+贪婪,因此它与@s0 else匹配,而不仅仅是@s0 要使其不贪婪,请使用.+? 代替:

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这里更好。

如果我错了,请指正我,但是RE不利于解析,因为它仅对Type2语言有效。 例如,您不能决定天气(((())()))是没有“计数”的有效语句,而regex则不能。 或者,谈谈您的示例,如果找不到其他无效示例。 也许是混合使用扫描仪/解析器,在这种情况下,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM