Parentheses
Parentheses can remember text matched by the subexpression they enclose.
#!/bin/sh
: "Backreference
Parentheses can remember text matched by subexpression
([a-z]) \1
You can have more than one set of parentheses
Use \1, \2, etc to refer to first, second / -o only-matches
Other uses of parantheses:
To limit the scope of alternation (a|b)
To group multiple characters to apply quantifiers (abc)?
"
A='
the the theory
the theory
an an answer
an answer
cat cat category
cat category
'
echo $A | grep '\<the +the\>' -o -E | tee result.txt
echo $A | grep '\<(an) +\1\>' -o -E | tee result.txt -a
echo $A | grep '\<([a-z]+) \1\>' -o -E | tee result.txt -a
echo $A | grep '\<([a-z]+) \1\>' -E --colour

the the
an an
the the
an an
cat cat
Questions and answers
Can you use parenthesis to group for backreference?
- a) yes
- b) no
In regex parenthesis are NOT used to:
- a) limit the scope of alternation
- b) negate character class
Multiple backrefenences, lke \1, \2, etc are allowed.
- a) false
- b) true
Which regex is used to replace doubled word?
- a) \b(word) +\1\b
- b) \b([a-zA-Z]+) +\1\b
Which metasequence is used for backreference? [a,3]
- a) \1
- b) $1
- c) {1}