Skip to content
Tcl Source Code View Ticket
Login

View Ticket

Match error with regexp

Closed / Duplicate504785ffffffffffffffffffffffffffffffffffCreated 25 years agoUpdated 23 years ago
Descriptionplain2002-01-17 09:36:12
In some cases regular expressions seem to match the
shortest string instead of the longest string. As
reported in comp.lang.tcl:

As reported in comp.lang.tcl on 16th Jan 2002:

tclsh>puts $tcl_patchLevel
7.4p2
tclsh>regexp {([^_.]*)([^.]*)\.(..)(.).*}
bbcos_001_c01.q1la _ m(1) m(2); parray m
m(1) = bbcos
m(2) = _001_c01

(Correct)


% puts $tcl_patchLevel
8.3.1
% regexp {([^_.]*)([^.]*)\.(..)(.).*}
bbcos_001_c01.q1la _ m(1) m(2); parray m
m(1) = c01
m(2) = 

Now the re_syntax manual page states, quite rightly,
that expressions match
the first string they find and (assuming default
arguments) will proceed to
gobble up the maximum length of input.

So [^_.]* should start at the beginning ("b") and
extend up to the first
underscore; ie "bbcos". The dot in here is superfluous,
and removing it cures
the "problem", as does forcibly anchoring it to the
start of the match:

% puts $tcl_patchLevel
8.3.1
% regexp {([^_]*)([^.]*)\.(..)(.).*} bbcos_001_c01.q1la
_ m(1) m(2); parray m
m(1) = bbcos
m(2) = _001_c01
% regexp {^([^_.]*)([^.]*)\.(..)(.).*}
bbcos_001_c01.q1la _ m(1) m(2); parray m
m(1) = bbcos
m(2) = _001_c01


Michael Cleverly posted a useful follow up outlining
the results from different tcl versions:

Looks like a bug to me.  Given your first regular
expression, these are
the results I get:

    m(1) = bbcos
    m(2) = _001_c01

with Tcl 7.0, 7.1, 7.3, 7.4, 7.5, 7.5p1, 7.6, 7.6p2,
8.0, 8.0p2, 8.0.3,
8.0.4, and 8.0.5;

    m(1) =
    m(2) = _c01

with Tcl 8.1.0 and 8.1.1; and, last, but not least:

    m(1) = c01
    m(2) =

with Tcl 8.2.0, 8.2.1, 8.2.2, 8.2.3, 8.3.0, 8.3.1,
8.3.2, 8.3.3, 8.3.4,
8.4a2, and 8.4a3.

Your two alternate regular expressions, that worked for
you under both 7.6
and 8.3 work fine on all the above versions too, as do
these additional
variants:

set RE4 {([^_.]*)([^.]*)}
set RE5 {([^_.]+)([^.]*)\.(..)(.).*}
set RE6 {([^_.]*)([^.]+)\.(..)(.).*}
set RE7 {([^_.]*)([^.]*).(..)(.).*}

It almost seems as if beginning with Tcl 8.1 the regex
engine is treating
the first two sets of parenthesis as non-greedy & is
looking for the
shortest match, though [regexp -about] doesn't show
REG_USHORTEST.
dgp Ticket [504785ffff]: 1 change [History diff]2003-11-13 05:18:08
dgp Ticket [504785ffff]: 1 change [History diff]2003-11-13 08:17:30
pvgoranplain2003-11-16 01:07:14
Logged In: YES 
user_id=383758

The cause of (and the resolution for) this bug is the same as 
for bug 505048.
Log in (anonymous is fine) to add a comment.