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>

<blockquote>
  <p>Expected output: <code>mydict = {"A":"text, hello", "B":"more text", "C":"something"}</code></p>
</blockquote>

<pre><code>import re

s = "[A] text [B] more text [C] something ... [A] hello"

pattern = r'\[([A-Z])\]([ a-z]+)'

items = re.findall(pattern, s)

output_dict = {}

for x in items:
    if x[0] in output_dict:
        output_dict[x[0]] = output_dict[x[0]] + ', ' + x[1].strip()
    else:
        output_dict[x[0]] = x[1].strip()

print(output_dict)
</code></pre>

<p><code>&gt;&gt;&gt; {'A': 'text, hello', 'B': 'more text', 'C': 'something'}</code></p>

python regex