I would like to be able to match a string literal with the option of escaped quotations. For instance, I’d like to be able to search ‘this is a ‘test with escaped\’ values’ ok’ and have it properly recognize the backslash as an escape character. I’ve tried solutions like the following:
import re regexc = re.compile(r'\'(.*?)(?<!\\)\'') match = regexc.search(r''' Example: 'Foo \' Bar' End. ''') print match.groups() # I want ('Foo \' Bar') to be printed above
After looking at this, there is a simple problem that the escape character being used, ‘\‘, can’t be escaped itself. I can’t figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:
# ... re.compile(r'\'(.*?)(?<!\\(\\\\)*)\'') # ...
Any regex gurus able to tackle this problem? Thanks.
I think this will work:
The regular expression
r'(?:^|[^\\])'(([^\\']|\\'|\\\\)*)''is forward matching only the things that we want inside the string:EDIT:
Add extra regex at front to check for first quote escaped.