Matching multiple patterns in a string
<p>I have a string that looks like that:</p>

<pre><code>s = "[A] text [B] more text [C] something ... [A] hello"
</code></pre>

<p>basically it consists of <code>[X] chars</code> and I am trying to get the text "after" every <code>[X]</code>.</p>

<p>I would like to yield this dict (I don't care about order):</p>

<pre><code>mydict = {"A":"text, hello", "B":"more text", "C":"something"}
</code></pre>

<p>I was thinking about a regex but I was not sure if that is the right choice because in my case the order of [A], [B] and [C] can change, so this string is valid too:</p>

<pre><code>s = "[A] hello, [C] text [A] more text [B] something"
</code></pre>

<p>I don't know how to properly extract the string. Can anyone point me to the right direction? Thanks.</p>

<p>Here's a simple solution:</p>

<pre class="lang-or-tag-here prettyprint-override"><code>#!/usr/bin/python

import re
s = "[A] text [B] more text [C] something ... [A] hello"
d = dict()
for x in re.findall(r"\[[^\]+]\][^\[]*",s):
    m = re.match(r"\[([^\]*])\](.*)",x)

    if not d.get(m.group(1),0):
        #Key doesn't already exist
        d[m.group(1)] = m.group(2)
    else:
        d[m.group(1)] = "%s, %s" % (d[m.group(1)], m.group(2))

print d
</code></pre>

<p>Prints:</p>

<pre><code>{'A': ' text ,  hello', 'C': ' something ... ', 'B': ' more text '}
</code></pre>

python regex