rubymom
rubymom

Reputation: 11

python combining 2 regexes that search strings within single and double quotes

I have a regex that extracts everything between 2 double quotes and another regex that does the same for 2 single quotes. The strings within the quotes can include escaped quotes. I'd like to make these 2 expressions into a single one:

1) re.findall(r'"(.*?)(?<!\)"', string)

2) re.findall(r"'(.*?)(?<!\)'", string)

So something like:

1+2) re.findall(r"'|\"(?<!\)['|\"]", string)

but this isn't working.

I'd like to have 'abc\"\"' "abc\'\'" be evaluated using the same regex. 'abc\"\"" isn't expected to work. If the quotes were exchanged, allow the same regex to work on it also. Is it possible?

Upvotes: 0

Views: 83

Answers (1)

Tryph
Tryph

Reputation: 6219

not sure i understood exactly what you wanted but it is possible to reuse the value of captured group in a regex.
may the following pattern do the job:
(['"])(.*)\1

explanation:
(['"]) : a quote or double-quote is captured as first group
(.*) : the second group captures everything...
\1 : ...until the first group value is met again
the result is available in the second group

Upvotes: 0

Related Questions