by miloignis · 5y ago · 0 comments
Because the idea is to match Tarzan, but only if it is not preceded and followed by a quote.
Regex intersection and complement do not perform look-behind or trailing context.
Live demo:
This is the TXR Lisp interactive listener of TXR 265.
Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet.
TXR may be used in areas that are not necessarily well ventilated.
1> [#/Tarzan&~"Tarzan"/ "Jane shouted, \"Tarzan\""]
"Tarzan"
2> [#/Tarzan&~"Tarzan"/ "Jane shouted, \"Tarzan!\""]
"Tarzan"
The &~"Tarzan" makes absolutely no difference. The reason is that Tarzan matches exactly one string. The complement ~"Tarzan" matches a whole countable infinity of strings, and one of those is Tarzan. The intersection of that infinity and Tarzan is therefore Tarzan.Intersection with complement is useful like this:
Search for a three-character substring that is not cat:
3> [#/...&~cat/ "hat"]
"hat"
4> [#/...&~cat/ "dog"]
"dog"
5> [#/...&~cat/ "doggy"
"dog"
6> [#/...&~cat/ "cat"]
nil
7> [#/...&~cat/ "scatter"]
"sca"
8> [#/...&~cat/ "catalan"] ;; "cat" is skipped, then "ata" works.
"ata"What you want is something like all matches of regex("Tarzan") not contained in a match for regex("\"Tarzan\""), which is a bit trickier. That would require something like:
regex("Tarzan") - all-substrings(regex("\"Tarzan\""))
and I'm not sure regular languages are closed over the "all-substrings" operation. Actually I'm pretty sure they aren't.
You have to be careful about inputs like this though: “Inside a string”Tarzan”Again inside a string”
My attitude is generally that one should use regexes for matching regular languages and if one needs a stack or even Turing completeness then handle that in code around the regex.
I’ll take that as a complement.