说明:1.在学习过程中没看到此论坛中有好的python实现,所以写一篇文章作为补充。
2.不赘述正则表达式和NFA的概念,着重描述python的算法实现,以及过程中用到的数据结构(十分精妙)。
创建NFA的第一步是解析正则表达式,我看龙书中使用分析树来解析的,在这里卡了一段时间,后来查资料发现Thompson的原论文用的解析法是将正则式从前缀形式转换成后缀形式,对我来讲同样清晰易懂而且好实现,实现的复杂度时间复杂度是O(n)。举例来说,原正则表达式为a.b,a|b,(a|b).c,(a|b)*那么转换后分别为ab., ab|, ab|c和ab|*(符号“.”表示联合,“|”表示或,“*”表示任意)。这个转换算法叫 Shunting Yard 算法:
def shunt(infix):
# Curly braces = dictionary
# *, | are repetition operators. They take precedence over concatenation and alternation operators
# * = Zero or more
# . = Concatenation
# | = Alternation
specials = {'*': 50, '.': 40, '|': 30}
pofix = ""
stack = ""
# Loop through the string one character at a time
for c in infi