Using regex, extract quoted strings that may contain nested quotes
<p>I have the following string:</p>

<pre class="lang-none prettyprint-override"><code>'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'
</code></pre>

<p>Now, I wish to extract the following quotes:</p>

<pre class="lang-none prettyprint-override"><code>1. Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!
2. How Doth the Little Busy Bee,
3. I'll try again.
</code></pre>

<p>I tried the following code but I'm not getting what I want. The <code>[^\1]*</code> is not working as expected. Or is the problem elsewhere?</p>

<pre><code>import re

s = "'Well, I've tried to say \"How Doth the Little Busy Bee,\" but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.'"

for i, m in enumerate(re.finditer(r'([\'"])(?!(?:ve|m|re|s|t|d|ll))(?=([^\1]*)\1)', s)):
    print("\nGroup {:d}: ".format(i+1))
    for g in m.groups():
        print('  '+g)
</code></pre>

<p>It seems difficult to achieve with juste one regex pass, but it could be done with a relatively simple regex and a recursive function:</p>

<pre><code>import re

REGEX = re.compile(r"(['\"])(.*?[!.,])\1", re.S)

S = """'Well, I've tried to say "How Doth the Little Busy Bee," but it all came different!' Alice replied in a very melancholy voice. She continued, 'I'll try again.' 'And we may now add "some more 'random test text'.":' "Yes it seems to be a good idea!" 'ok, let's go.'"""


def extract_quotes(string, quotes_list=None):
    list = quotes_list or []
    list += [found[1] for found in REGEX.findall(string)]
    print("found: {}".format(quotes_list))
    index = 0
    for quote in list[:]:
        index += 1
        sub_list = extract_quotes(quote)
        list = list[:index] + sub_list + list[index:]
        index += len(sub_list)
    return list


print extract_quotes(S)
</code></pre>

<p>This prints:</p>

<pre><code>['Well, I\'ve tried to say "How Doth the Little Busy Bee," but it all came different!', 'How Doth the Little Busy Bee,', "I'll try again.", 'And we may now add "some more \'random test text\'.":\' "Yes it seems to be a good idea!" \'ok, let\'s go.', "some more 'random test text'.", 'Yes it seems to be a good idea!']
</code></pre>

<p>Note that the regex uses the punctuation to determine if a quoted text is a "real quote". in order to be extracted, a quote need to be ended with a punctuation character before the closing quote. That is 'random test text' is not considered as an actual quote, while 'ok let's go.' is.</p>

<p>The regex is pretty simple, I think it does not need explanation.
Thue <code>extract_quotes</code> function find all quotes in the given string and store them in the <code>quotes_list</code>. Then, it calls itself for each found quote, looking for inner quotes...</p>

python regex