With regular expressions you can either back-reference a
)or you can specify that a match must
} it. The difference between one and the other is significant. For a simple example consider the string:
... when matched against the following two patterns:
For the first of these the grouping is actually irrelevant because the pattern searches for a single character - when specifying repetitions the the grouping is only important in that it can contain a whole subexpression to which the repetition can refer. And so, for this simple example case...
... and ...
...are synonymous and can be taken to mean that the match engine should look for the leftmost and longest string in input that is composed of two characters - either of b or a. The repetition applies to the pattern which makes the match and not to the contents of the match. So it literally means:
....in the same way...
...which would work ok for the single character a but which is not a good example of how to match a matched string a second time.
For our input sample this gets...
But the back-reference is very different - it is a reference to the content of the match. The simple example case gets...
...because that is the leftmost and longest string in input that is comprised of a character that matches the subexpression's
[ba] pattern and which is immediately followed by itself - not the pattern which matched the character.
So you want:
Because a regular expression pattern and the string which it matches are not the same - else we wouldn't have much call to use regular expressions in the first place. To demonstrate the difference with a slightly more complicated input example consider the following:
printf %s\\n 123ABC321 123ABC123 321ABC321 |
grep above will print:
...because in every case the pattern is successfully matched twice. But if the
grep line were replaced with:
... it would only print ...