Regex pattern behaving differently in TCL compared with Perl & Python
<p>I am trying to extract a sub-string from a string using regular expressions. Below is the working code in <code>Python</code> (giving desired results)</p>

<p><strong>Python Solution</strong></p>

<pre><code>x = r'CAR_2_ABC_547_d'
&gt;&gt;&gt; spattern = re.compile("CAR_.*?_(.*)")
&gt;&gt;&gt; spattern.search(x).group(1)
'ABC_547_d'
&gt;&gt;&gt;
</code></pre>

<p><strong>Perl Solution</strong> </p>

<pre><code>$ echo "CAR_2_ABC_547_d" | perl -pe's/CAR_.*?_(.*)/$1/'
ABC_547_d
</code></pre>

<p><strong>TCL Solution</strong> </p>

<p>However, when I try to utilize this approach in <code>Tcl</code>, it is giving me different results. Can someone please comment on this behavior</p>

<pre><code>% regexp -inline "CAR_.*?_(.*)" "CAR_2_ABC_547_d"
CAR_2_ {}
</code></pre>

<blockquote>
  <p>A branch has the same preference as the first quantified atom in it
  which has a preference.</p>
</blockquote>

<p>So if you have <code>.*</code> as the first quantifier, the whole RE will be greedy,
and if you have <code>.*?</code> as the first quantifier, the whole RE will be non-greedy.</p>

<p>Since you have used the <code>.*?</code> in the first place itself, the further expression follow lazy mode only. </p>

<p>If you add end of line <code>$</code>, then it will match the whole. </p>

<pre><code>% regexp -inline "CAR_.*?_(.*)$" "CAR_2_ABC_547_d"
CAR_2_ABC_547_d ABC_547_d
</code></pre>

<p><strong>Reference :</strong> <a href="https://www.tcl.tk/man/tcl8.6/TclCmd/re_syntax.htm#M95" rel="nofollow">re_syntax</a></p>

python perl tcl tclsh