用于匹配代码中字符串语法的正则表达式

Regex to Match String Syntax in Code

假设有一个 Python 源代码文件,例如:

def someStuff():
  return "blabla"

myThing = "Bob told me: \"Hello there!\""

twoStrings = "first part " + "second part"

我将如何编写一个正则表达式来匹配:

"blabla""Bob told me: \"Hello there!\"""first part "、&"second part"

包括周围的引号?


最初,我认为这可以通过 \"[^\"]*\" 简单地完成,但是这没有考虑到字符串包含 \" 的情况。我也尝试过加入负面回顾:

(?<!\)\"[^\"]*(?<!\)\"

但没有取得任何成功。推荐的处理方法是什么?

使用负向后视:

".*?(?<!\)"

这使用惰性量词 (*?) 来匹配直到下一个引号 ("),只要引号没有被反斜杠转义 (\")。与更简单(但错误)的正则表达式 ".*?"

进行比较

此正则表达式(带有单行修饰符 s)应匹配所有类型的字符串文字:

([bruf]*)("""|'''|"|')(?:(?!)(?:\.|[^\]))*

这支持三引号字符串、转义序列,它还捕获任何前缀,如 rufb。见 online demo.

需要单行修饰符 s 才能正确匹配多行字符串。此外,启用 i 修饰符可使其匹配大写前缀,例如 R'nobody uses capitalized prefixes anyways'.


据我所知,有两个注意事项:

  1. 它也匹配字节文字。
  2. 它匹配注释中的字符串文字。

正则表达式的解释:

([bruf]*)          # match and capture any prefix characters
("""|'''|"|')      # match the opening quote
(?:                # as many times as possible...
    (?!)         # ...as long as there's no closing quote... 
    (?:            # ...match either...
        \.        # ...a backslash and the character after it
    |              # ...or...
        [^\]      # ...a single non-backslash character
    )        
)*
                 # match the closing quote