Quotes text regex that ignores backslashes

Viewed 126

I need a regex that would get all the text inside quotes ( ", ' ) For Example:

import re
i = 'Test Text 1 "Test Text 2"'
re.compile(regex).findall(i)
# Returns: ['"Test Text 2', '"']

Till now, I've made this regex:

regex = ("(')([^']+)?|(\")([^\"]+)?")

And this works pretty well, tho there is a problem. I want it to work like python quotes color coding system, so I want it to not stop the element if there is a backslash before the end quote. For Example:

import re
i = 'Test Text 1 "Test Text \\" 2"'
re.compile(regex).findall(i)
# Returns: ['"Test Text " 2', '"']
1 Answers

Use

import re
i = 'Test Text 1 "Test Text \\" 2"'
regex = r"(['\"])((?:\\.|(?!\1)[^\\])*)\1"
print( re.compile(regex, re.DOTALL).findall(i) )
# => [('"', 'Test Text \\" 2')]

See proof and Python demo.

The (['"])((?:\\.|(?!\1)[^\\])*)\1 pattern matches any quote in Group 1 and then matches any escape sequence (with \\.) or any character other than the quote captured and backslash ((?!\1)[^\\]), zero or more times, up to the quote captured (see \1).

Related