简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM