Match quoted strings with regular expressions

October 11, 2021 - Tags: python, re

The following regular expression is handy to match quoted strings that may contain escaped quotes:

import re

r = re.compile(r'"(?:(?!(?<!\\)\").)*"')

Here (?<!\\)\" matches a quote which is not preceded by a backslash (i.e. an unescaped quote). So (?!(?<!\\)\") is a lookahead which ensures that the next character is not an unescaped quote.