2

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', '"']
2
  • Does this hyphothetical regex need to ignore the backslash-before-quote if there are two backslashes? (.. Actually any even number of backslashes.)
    – Jongware
    Jul 2, 2020 at 14:59
  • no. If its '"Test Text \\\\"' then it should not ignore it, as I said, exactly like python quotes color coding. Basically as you said, even number of backslashes shouldn't be ignored
    – Ultra
    Jul 2, 2020 at 15:04

1 Answer 1

0

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).

1
  • Thanks. This works, but when there isn't an end quote, it claims the quote with the backslash behind it as the end quote. For example: i = 'Test Text 1 "Test Text \\" 2'
    – Ultra
    Jul 5, 2020 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.