Regex: Back reference and Self reference in Regular Expressions

This is going to be a very short and niche post.

Sometimes I have to use regular expression or “regex” searches to parse a bunch of text, but I can’t remember how to use the search function to find a particular sequence of character and then reuse those found characters in the text I’m trying to replace it with.  In Notepad++, this would be done as follows:

  • Search string:   (7//*[0-9]*[0-9])\r\n
    • This will find all entries with “7/3” or “7/14” or similar digits with a line return afterwards
  • Replace string:  \1/2018;
    • This will replace those entries with “7/3/2018;” and “7/14/2018;”, respectively

The trick here is that the first set of search information is collected together within a set of parenthesis, which are then referenced back by the “\1”.  If you forget the parenthesis, the “\1” term won’t “know” what it’s supposed to be repeating.

Like I said, very niche.