What is Backreference in regular expression?
A backreference in a regular expression identifies a previously matched group and looks for exactly the same text again. A simple example of the use of backreferences is when you wish to look for adjacent, repeated words in some text. The first part of the match could use a pattern that extracts a single word.
What is a back reference?
back-references are regular expression commands which refer to a previous part of the matched regular expression. Back-references are specified with backslash and a single digit (e.g. ‘ \1 ‘). In a regular expression pattern, back-references are used to match the same content as a previously matched subexpression.
What is sed for?
sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed ), sed works by making only one pass over the input(s), and is consequently more efficient.
When to use back references and subexpressions in SED?
Back-references and subexpressions are used in two cases: in the regular expression search pattern, and in the replacement part of the s command (see Regular Expression Addresses and The “s” Command ). In a regular expression pattern, back-references are used to match the same content as a previously matched subexpression.
Which is part of a regular expression does a back reference refer to?
back-references are regular expression commands which refer to a previous part of the matched regular expression. Back-references are specified with backslash and a single digit (e.g. ‘ 1 ’). The part of the regular expression they refer to is called a subexpression, and is designated with parentheses.
When to use back references in replacement part?
In the s command, back-references can be used in the replacement part to refer back to subexpressions in the regexp part. The following example uses two subexpressions in the regular expression to match two space-separated words. The back-references in the replacement part prints the words in a different order:
Why do I use regex instead of SED?
Probably the regex is not completely correct, but I don’t know why. The problem is quoting. Because you don’t quote your sed command, the parenthesis \\ (…\\) was interpreted by the shell before passing to sed. So sed treated them as literal parenthesis instead of escaped parenthesis, no back-reference affected.