Python - 如何忽略正则表达式中的转义字符

Python - how to ignore escape chars in regexp

我的目标是识别此模式:

STR("<some_string>")

我已经构建了这个正则表达式:

(STR\()"(.+?)("\))

这在大多数情况下工作正常,但在这个例子中失败:

STR("test \") string")

在上面的例子中我希望得到 test \") string

我建议你添加一个否定的回顾断言。

(STR\()"(.+?)(?<!\)("\))

DEMO

示例:

>>> s1 = r'STR("<some_string>")'
>>> s2 = r'STR("test \") string")'
>>> re.findall(r'STR\("(.+?)(?<!\)"\)', s1)
['<some_string>']
>>> re.findall(r'STR\("(.+?)(?<!\)"\)', s2)
['test \") string']

(?<!\)" 基于否定后向断言的模式会断言双引号前面不会有反斜杠字符。

STR\("((?:\"|[^"])*)"\)

DEMO