Skip to content

Instantly share code, notes, and snippets.

@casallas
Last active August 29, 2015 14:13
Show Gist options
  • Save casallas/62e900816c28d5968268 to your computer and use it in GitHub Desktop.
Save casallas/62e900816c28d5968268 to your computer and use it in GitHub Desktop.
ag/ack/atom regex example

Suppose you want to change the following

original new
a \ttimes b -> =
a \\ttimes b -> =
a_2 \ttimes b -> a_2 \btimes b
a_2 \\ttimes b -> a_2 \\btimes b
a_{2} \ttimes b -> a_{2} \btimes b
a_{2} \\ttimes b -> a_{2} \\btimes b
a_{V[i]} \ttimes b -> a_{V[i]} \btimes b
a_{V[i]} \\ttimes b -> a_{V[i]} \\btimes b

Finding the cases that need substitution is easy

ag "_\\{?([A-Za-z0-9-]*)?(\\[(?1)\\])?\\}? *\\\?\\\ttimes"

But this will select everything starting from the underscore

  • a _2 \ttimes b
  • a _2 \\ttimes b
  • a _{2} \ttimes b
  • a _{2} \\ttimes b
  • a _{V[i]} \ttimes b
  • a _{V[i]} \\ttimes b

but really you only want to select only ttimes

  • a_2 \ttimes b
  • a_2 \ttimes b
  • a_{2} \ttimes b
  • a_{2} \ttimes b
  • a_{V[i]} \ttimes b
  • a_{V[i]} \ttimes b

Lookbehind would the solution, so really you only need to enclose the part in the regex preceding ttimes within (?<=...), i.e.

ag "(?<=_\\{?([A-Za-z0-9-]*)?(\\[(?1)\\])?\\}? *\\\?\\\)ttimes"

sadly, ack/ag don't support variable length expressions within the lookbehind expression, so you would get the following error:

ERR: pcre_compile failed at position 42. Error: lookbehind assertion is not fixed length

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment