Skip to content

Comment on Describing and Inventing a New Regular Expression Quantifier

Comments

Yeah, the possessive quantifier looks like that it simply disables backtracking but it also silently makes the matching greedy. It should really have been orthogonal: `a+` is greedy and backtrackable, `a+?` is non-greedy and backtrackable, `a++` is greedy and atomic, and `a+?+` is non-greedy and atomic. It's not pretty, but multiple quantifiers were never pretty after all.

Or better, ditch the opportunistic use of otherwise invalid quantifier sequences and stick to the atomic group. Vim got this almost correct [1]:

              multi ~
         'magic' 'nomagic'  matches of the preceding atom ~
    
    |/\{|   \{n,m}  \{n,m}  n to m          as many as possible
            \{n}    \{n}    n               exactly
            \{n,}   \{n,}   at least n      as many as possible
            \{,m}   \{,m}   0 to m          as many as possible
            \{}     \{}     0 or more       as many as possible (same as *)
    
    |/\{-|  \{-n,m} \{-n,m} n to m          as few as possible
            \{-n}   \{-n}   n               exactly
            \{-n,}  \{-n,}  at least n      as few as possible
            \{-,m}  \{-,m}  0 to m          as few as possible
            \{-}    \{-}    0 or more       as few as possible
    
    |/\@>|  \@>     \@>     1, like matching a whole pattern
So a non-greedy and atomic pattern would be `\%(a\{-}\)\@>`. Unfortunately you can't write `a\{-}\@>` and have to wrap `a\{-}` into a non-capturing group though.

[1] https://vimhelp.org/pattern.txt.html#pattern-overview

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.