grep – Difference Between [] and \(\) in Basic Regular Expression

grepregular expression

Consider:

$ echo '<H1>heading</H1>' | grep '<H\(1\|3\|2\)>.*</H\1>'
$ <H1>heading</H1>

and

$ echo '<H1>heading</H3>' | grep '<H[1-3]>.*</H\1>'
$ grep: Invalid back reference

first command works just fine.

  1. Doesn't [1-3] and \(1\|3\|2\) both mean 1 or 2 or 3 ? if not why? and what the difference between them?
  2. why back-reference works with only \(\) ?

Best Answer

  • () means «groupping» which means set a part of the string which can operate as 1 item, and for backrefference too.
  • [] means symbols set

So if you use parenthesis just for single symbols the meaning is same. But usually it used for multisymbol strings like (cat|dog)

Related Question