Retrieving log message within curly braces using Regex with Python
<p>I am trying to parse some logs which return some responses in a key-pair format. I only want they value contained by the last key-pair (Rs: {".."}). The information I want are enclosed inside the curly braces.</p>

<p>What I have done is to use regex to match anything inside the curly braces like this:</p>

<pre><code>import re

log = '2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"data": "blah blah"}'

text = re.compile("Rs\:{(.*)\}").search(log).group(1)
print (text)

&gt;&gt;&gt; "data": "blah blah"

# Desired results
&gt;&gt;&gt; {"data": "blah blah"}
</code></pre>

<p>However there are some issues doing it this way:</p>

<ol>
<li><p>I also wanted the starting curly braces and closing curly braces.</p></li>
<li><p>This method doesn't work if there other opening ("{") or closing ("}:) curly braces before or inside the Rs values.</p></li>
</ol>

<p>Is there a better way to do this?</p>

<p>It seems that you need two things: re-adjust the first capturing group boundaries to include curly braces, and use a lazy version of <code>.*</code> (in case there are multiple values in the string). I also recommend checking if there is a match first  if you are using <code>re.search</code>, or just use <code>re.findall</code></p>

<pre><code>import re
log = '2016-10-13 17:04:50 - info - uri:"GET x/y/z" ip:1.1.1.1 Rs:{"data": "blah blah"}'
text = re.compile(r"Rs:({[^}]*})").search(log)
if text:
    print (text.group(1))
# or
print(re.findall(r"Rs:({[^}]*})", log))
</code></pre>

<p>See the <a href="https://ideone.com/XW2ots" rel="nofollow">Python demo online</a></p>

<p><strong>Pattern details</strong>:</p>

<ul>
<li><code>Rs:</code> - a whole word <code>Rs</code> and a <code>:</code></li>
<li><code>({[^}]*})</code> - Group 1 capturing

<ul>
<li><code>{</code> - a literal <code>{</code></li>
<li><code>[^}]*</code> - 0+ chars other than <code>}</code> (see <a href="http://www.regular-expressions.info/charclass.html#negated" rel="nofollow">more details on <em>Negated Character Classes</em> here</a>)</li>
<li><code>}</code> -  a literal <code>}</code>.</li>
</ul></li>
</ul>

python regex