Capture groups can be used to do the following:
Search Text: Blake Robertson
Find RegEx: (.*) (.*)
Replace RegEx: $2 $1
will change the text to: Robertson Blake
The $1 in the Replace RegEx matches to the first (.*) in the find expression and the $2 matches the second (.*)
More practical example… in my code i had a bunch of log statements like debug(“hello world\r\n”); I was running low on program space in my PIC microprocessor and decided to replace them all with something like debugln(“hello world”); which saves us a whopping two bytes.
If you want to replace a portion of line of code and you want to keep the actual print statement (the hello world part) you have to use a capture group.
Here’s the first regular expression i came up with:
FIND: debug\(\"(.*)\\r\\n"\); REPLACE: debugln\(\"$1\"\);
This works and illustrates that whatever was originally in the (.*) will be inserted into the replacement string where the $1 is.
Here is the final FIND, REPLACE combo i came up with which would also work with a string which has additional printf style arguments and optional whitespace in various parts of the expression such as:
debug( “sum = %u\r\n”, x ) ;
FIND: debug\(\s*\"(.*)\\r\\n\"(.*)\)\s*; REPLACE: debugln\(\"$1\"$2\);
Note: my replace expression eliminates any of the white space that was matched in the FIND expression.