我相信 Lark 使用的是普通的 Python 正则表达式,所以你可以使用否定的前瞻断言来排除关键字。但是您必须注意不要拒绝以关键字开头的名称:
ID: /(?!(else|call)\b)[a-z_][a-z0-9]*/i
这个正则表达式当然适用于 Python3:
>>> # Test with just the word
>>> for test_string in ["x", "xelse", "elsex", "else"]:
... m = re.match(r"(?!(else|call)\b)[a-z_][a-z0-9]*", test_string)
... if m: print("%s: Matched %s" % (test_string, m.group(0)))
... else: print("%s: No match" % test_string)
...
x: Matched x
xelse: Matched xelse
elsex: Matched elsex
else: No match
>>> # Test with the word as the first word in a string
... for test_string in [word + " and more stuff" for word in ["x", "xelse", "elsex", "else"]]:
... m = re.match(r"(?!(else|call)\b)[a-z_][a-z0-9]*", test_string)
... if m: print("%s: Matched %s" % (test_string, m.group(0)))
... else: print("%s: No match" % test_string)
...
x and more stuff: Matched x
xelse and more stuff: Matched xelse
elsex and more stuff: Matched elsex
else and more stuff: No match