2 ms·
From the article: > I will suggest, rather opinionatedly, that possessive quantifiers aren't particularly useful. I will suggest the opposite, that possessive
by jlokier 6y ago
From the article:
> I will suggest, rather opinionatedly, that possessive quantifiers aren't particularly useful.
I will suggest the opposite, that possessive quantifiers are so useful they should have been the default, as backtracking causes problems of performance and accidental mismatching that you usually don't want.
Backtracking is a really useful invention. But it should not be used on every term.
I default to using possessives more often than not these days. I've writte a lot of parsers over the years where regexes played a role, and this is what I found in practice.
Now, a non-possessive quantifier makes me stop and think if it should be there, and what kind of problem is it hiding. Usually it doesn't matter, especially when the regex is being used on "known" data, but occasionally it's hiding a subtle parsing bug.
For example, any regex that is matching whitespace-separated terms. For the whitespace, which makes more sense, "\s+" or "\s++"?
The latter. Backtracking over whitespace is just a waste of time; it won't change what is matched, and if it does, that's usually a bug in the rest of the regex.
What about matching words in a parser of a typical programming language, does it make more sense to write "\w+" or "\w++"? The latter again. You do not want to accidentally treat "iffy" as though it's an "if" followed by "fy".
You can explicitly require a word boundary or a non-word character after the word. But which is more straightforward (and faster) out of "\w++", "\w+\b" and "\w+(?:\W|$)"?