How to write a regex in Python with named groups to match this?
<p>I have a file which would contain the following lines.</p>

<p>comm=adbd pid=11108 prio=120 success=1 target_cpu=001</p>

<p>I have written the following regex to match.</p>

<pre><code>_sched_wakeup_pattern = re.compile(r"""
comm=(?P&lt;next_comm&gt;.+?)
\spid=(?P&lt;next_pid&gt;\d+)
\sprio=(?P&lt;next_prio&gt;\d+)
\ssuccess=(?P&lt;success&gt;\d)
\starget_cpu=(?P&lt;target_cpu&gt;\d+)
""", re.VERBOSE)
</code></pre>

<p>But now I've lines like the following also where the success component isn't there.</p>

<p>comm=rcu_preempt pid=7 prio=120 target_cpu=007</p>

<p>How do I modify my regex here to match both the cases? I tried by putting a * everywhere in that line containing "success", but it throws errors.</p>

<p>Matching <code>0</code> or <code>1</code> repetitions do  <code>(your_string)?</code>.</p>

<pre><code>_sched_wakeup_pattern = re.compile(r"""
comm=(?P&lt;next_comm&gt;.+?)
\spid=(?P&lt;next_pid&gt;\d+)
\sprio=(?P&lt;next_prio&gt;\d+)
\s?(success=(?P&lt;success&gt;\d))?
\starget_cpu=(?P&lt;target_cpu&gt;\d+)
""", re.VERBOSE)
</code></pre>

<p>There you go
Here it looks for the whole string so, it also print <code>success=</code>:</p>

<pre><code>output =&gt;
('rcu_preempt', '7', '120', '', '', '007')
('kworker/u16:2', '73', '120', '', '', '006')
('kworker/u16:4', '364', '120', '', '', '005')
('adbd', '11108', '120', 'success=1', '1', '001')
('kworker/1:1', '16625', '120', 'success=1', '1', '001')
('rcu_preempt', '7', '120', 'success=1', '1', '002')
</code></pre>

<p>now we need to figure out a way to remove that <code>"success="</code>. That doesn't seem difficult.</p>

<p>[edited]<br>
<code>(?:\ssuccess=)?(?P&lt;success&gt;\d)?</code> works just nicely.<br>
by <a href="http://stackoverflow.com/users/3185459/romanperekhrest">RomanPerekhrest</a></p>

python regex regex-group