Skip to content
Tcl Source Code View Ticket
Login

View Ticket

Non-greedy quantifiers revert to greedy when branched

Closed / Duplicate2798939fffffffffffffffffffffffffffffffffCreated 18 years agoUpdated 42 days ago
Descriptionplain2009-05-30 21:15:37
Non-greedy quantifiers revert to greedy when used in conjunction with branches (pipe character).

The following branch-free expression matches each letter in the test string and therefore correctly returns 14
regexp -all .+? {this is a test}

The following branched expression matches the entire string only once because the quantifier reverts to greedy and therefore incorrectly returns 1
regexp -all .+?|x {this is a test}

This breaks a lot of complex regular expressions that require non-greedy quantifiers and branches.
dkfplain2009-05-31 16:55:25
IIRC, the problem is that the "first" quantifier in the syntax tree is the alternation, which can't be made non-greedy. The fix is to use {1,1}? to force the whole RE to be non-greedy (a non-capturing paren is also needed, but that's pretty trivial).

% regexp -all (?:.+?|x){1,1}? {this is a test}
14

Note that this is different from Perl/PCRE; they use a different model for greedy/non-greedy handling that does this in a way that is more as people intuitively expect (in return for being worse in other cases).
bilgexaplain2009-05-31 18:47:22
Surely you realise that this "fix" cannot possibly apply to complex alternations. The non-greedy quantifiers within the alternation group are all broken and this functionality can never be replaced by a single quantifier on the group as a whole.
dramplain2017-10-26 01:36:45
Still true for 8.6.6

But this behaviour is stated clearly in re_syntax(n) as:

  An RE consisting of two or more branches connected by the | operator prefers longest match.

BTW, PostgreSQL has same behaviour. (confirmed in PG 9.6.4)
dgpplain2017-10-26 02:10:01
Tcl and postgres make use of (forks of)
the same regexp engine.
serhiy.storchakawiki2026-10-11 10:49:37

Documented: an RE with a top-level | prefers the longest match. (?:.+?|x){1,1}? makes it prefer the shortest; regexp -all then returns 14. The docs are clarified in branch doc-re-syntax-preference. Duplicate of [219219ffff].

serhiy.storchaka Closed ticket [2798939fff]. [History diff]2026-10-11 10:52:40
serhiy.storchaka Ticket [2798939fff]: 3 changes [History diff]2026-10-22 17:19:24
Log in (anonymous is fine) to add a comment.