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>Not sure if this is quite what you're looking for but it fails with duplicates</p>

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

results = [text.strip() for text in re.split('\[.\]', s) if text]

letters = re.findall('\[(.)\]', s)

dict(zip(letters, results))

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

<p>Since the output looks like this:</p>

<pre><code>In [49]: results
Out[49]: ['hello,', 'text', 'more text', 'something']

In [50]: letters
Out[50]: ['A', 'C', 'A', 'B']
</code></pre>

<p>To solve for duplicate you could do something like....</p>

<pre><code>mappings = {}

for pos, letter in enumerate(letters):
    try:
        mappings[letter] += ' ' + results[pos]
    except KeyError:
        mappings[letter] = results[pos]
</code></pre>

<p>which gives: <code>{'A': 'hello, more text', 'B': 'something', 'C': 'text'}</code></p>

<p><strong>UPDATE</strong></p>

<p>Or even better you could look at using a default dict: as shown here: <a href="http://stackoverflow.com/questions/33091911/python-append-to-dictionary-from-a-zip">enter link description here</a></p>

python regex