3 ms·
This "trick" is simply exploiting a bug in regex implementations. The regex "Tarzan"|(Tarzan) should match the string "Tarzan" in two ways: first,
by rntz 11y ago
This "trick" is simply exploiting a bug in regex implementations.
The regex
"Tarzan"|(Tarzan)
should match the string
"Tarzan"
in two ways: first, matching the entire string; and second, matching the substring "Tarzan" in the whole string "\"Tarzan\"". But most regex implementations drop extra overlapping matches. I argue this is incorrect behavior, because it complicates understanding what a regex means - you have to understand the /order/ in which your regular expression matcher interprets your regular expression, which is an implementation detail. I conjecture that a DFA-based regex engine would not be able to exhibit this order-biased behavior, at least not with the standard approach.
However, it's interesting that this "bug" turns out to be a "feature" for the case of excluding other behavior. I'm not sure what conclusion to draw from this.
- GhotiFish 11y agoGiven a string "aaabbb" what should the results be, of the regular expression "(aa|aaa)(abbb|bbb)"? $1 = ? $2 = ?
- rntz 11y agoI believe it matches in three ways: - the whole string, grouped as "(aa)(abbb)", - the whole string, grouped as "(aaa)(bbb)"; - the substring "aabbb", grouped as "(aa)(bbb)".
- GhotiFish 11y agoSorry, I made an assumption there that you were talking about the practical applications of regex, not the theoretical applications, and I was asking you to explain how you would practically return multiple matches in... any environment. This was a small regex designed to create multiple answers to see how you resolved the issue, obviously we can engineer regexes that return far more results. So something's got to give. I don't agree with you that regex's innately imply all matches are valid.
- rntz 11y agoThe original article already relies on finding multiple matches, in order to ignore the matches that don't contain the group that we're interested in. Python's regex library, for example, can return multiple matches. It has three functions: - `re.match`, which checks whether the whole string matches. - `re.search`, which checks for the first location in the string that matches. - `re.findall`, which finds "all" non-overlapping matches. I was simply suggesting that the "non-overlapping" constraint in findall is a "bug", in some sense, because it exposes implementation details of the regex engine. But, again, given that it is apparently a useful bug, maybe I am wrong. But that leaves open the question what the right spec for regex matching is, anyway.