python - 如何从正则表达式中排除某些可能性?

标签 python regex parsing regex-group lark-parser

对于我正在创建的解析器,我使用此正则表达式作为 ID 的定义:

ID: /[a-z_][a-z0-9]*/i

(对于任何不熟悉我正在使用的特定解析器语法的人来说,“i”标志仅意味着不区分大小写。)

我还有一些关键字,例如:

CALL_KW: "call"
PRINT_KW: "print"

问题是,由于语法中的一些歧义,有时关键字被视为 ID,但我真的不希望它们被视为 ID。所以我在想是否可以重写ID的正则表达式,使得关键字根本不与它匹配。这样的事可能吗?

为了提供更多背景信息,我使用 Lark Python 的解析器库。 Lark 提供的 Earley 解析器(与动态词法分析器一起)在处理不明确的语法方面非常灵活和强大,但它们有时会做这样奇怪的事情(并且是非确定性的!)。因此,我试图通过使关键字永远不匹配 ID 规则来为解析器提供一些帮助。

最佳答案

我相信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

关于python - 如何从正则表达式中排除某些可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098140/

相关文章:

performance - 启用某些规​​则时,UU-Parsinglib 会急剧变慢

Python foo > bar(输入文件,输出文件)

javascript - JavaScript 的 MAC 地址正则表达式

regexbuddy 有时不要回溯

c++ - 在 C++ 编译过程中,上下文敏感性在哪里得到解决?

python - 在 Python 中动态读取更新的文件

python - Redis 阻塞直到键存在

python - Tensorflow ValueError : Shapes (? , 1) 和 (?,) 不兼容

python - 错误 : <class 'socket.error' >, [Errno 2] 没有那个文件或目录 : file:/usr/lib/python2. 7/socket.py 行:228

regex - 在linux中使用正则表达式重命名文件