Regex lookarounds

rexegg.com provides a nice overview of uses for lookarounds.

  • Validation, without or before matching
  • Match anything from a set, except ... (subtraction)
    • with lookahead, subtraction of Q and K from set \w: (?![QK])\w
    • with lookbehind, subtraction of Q and K from set \w: \w(?![QK])
  • Add another condition to a set (intersection)
    • with lookahead, match intersection of set \w and \p{N}: (?=\p{N})\w (match word char if its also a number)
  • Limit the scope of a token,
    • e.g. tempered greedy token: match any token that is not followed by END: (?:(?!{END}).)*
    • So this is a .* that is limited in scope by an {END} delimiter! Super useful, because .* goes wild normally.
    • Opening delimiter: (?<=#START#).*: only start the match with a dot token if it's right after the start delimiter; then match everything to the right
    • Match up to, but not including: .*?(?=#END#)
    • Combined: (?<=#START#).*?(?=#END#)
  • Explicit Greedy Alternation: {START}(?:[^{]++|{(?!END}))*+{END}
    • Problem this solves: opening bracket of a delimiter such as {START} or {END} may also appear somewhere in between (but then not followed by "END}")
    • Also uses contrast:
    • 1) Either we encounter a character that is not a left opening bracket (left alternative)
    • 2) or we encounter a left opening bracket
      • we only want to further expand when the left bracket is not followed by "END}"
      • otherwise, stop the matching and match "{END}" (which we know is there due to the lookahead)
      • make *+ possessive so that if there is no {END} delimiter, you won't backtrack though the whole string
  • Inserting or splitting with zero-width matches.
    • Normally you'll match a character and than replace that character. In this manner the replace function can never add text.
    • But zero-width assertions such as lookarounds match an exact position (as it were "between" characters); replacing here can add characters in between
    • Example: this regex (?<=[a-z])(?=[A-Z]) can be used to convert CamelCase to Camel Case.
    • Apparently Python's re module does not split on zero-width matches, but most engines do (and the regex module as well)
  • Anchor lookaheads to avoid unnecessary steps
    • Either with \A, $ etc.
    • or with a literal match before the lookahead
  • TODO: back to the future lookbehind
  • TODO compounded lookahead and lookbehind
  • TODO infinite lookaround

TODO finish later.

Also see regex negative lookahead.