一种匹配包含括号的 Lisp 字符的方法

A way to match Lisp characters containing a parenthesis

我正在 Python 中编写 Lisp 解析器作为编译器项目的一部分。我的分词器是这样工作的:

def tokenize(filename):
    with open(filename, "r") as file:
        comment_free = remove_comments(file.read())
    return comment_free.replace("(", " ( ").replace(")", " ) ").split()

Lisp 字符有点不同:字符 a 将是 #\a( 将是 #\(,等等。对于包含左括号或右括号的字符,它们被分词器错误地分成两个单独的部分(#\())。

我可以将字符指示符与 [^#\] 匹配,括号与 \(|\) 匹配,但是我将如何创建一个模式来检查代码的一部分是否不以字符指示符开头并跟随用左括号或右括号?如果我能做出这样的模式,我就可以用周围有空格的括号替换所有这样的实例。我认为 ([^#\])(\(|\))* 会起作用,但并非在所有情况下都起作用。有没有精通正则表达式的人知道如何解决这个问题?

how would I create a pattern that checks if a part of the code does not start with a character indicator and follows with a left or right parenthesis?

您可以使用负向回顾来检查指示符是否在左侧,并使用字符 class 而不是交替来匹配 ()

(?<!#\)[()]

说明

  • (?<!#\) 负后视,断言直接在左边的不是 #\
  • [()] 匹配 ()

Regex demo


如果指标是 #\ 您可以使用 2 个字符 classes:

(?<![#\])[()]

Regex demo