what the different between these two regex expression ?

AB\{4\} and (AB)\{4\}

for the first expression I think that it repeat B 4 times, then for second expression it

repeats AB 4 times. When I try to test the second expression using ABABABAB nothing matches.

  • What tool are you using as a regex engine?
    – Joseph R.
    Mar 20 '13 at 23:12
  • I just tested in bash by creating a file and then use grep command Mar 20 '13 at 23:14
  • Try escaping the braces with a backslash
    – Joseph R.
    Mar 20 '13 at 23:18
  • sorry that was in the original question, I guess need to put \\ in order to show the backslash on stack exchange Mar 20 '13 at 23:20
  • 3
    Write it (AB){4} if it's a ERE, \(AB\)\{4\} if it's a BRE. Mar 20 '13 at 23:22

grep by default uses BREs, so you need to escape your parentheses:

grep 'AB\{4\}'
grep '\(AB\)\{4\}'

You can also use EREs by passing the -E option, available on some grep implementations:

grep -E 'AB{4}'
grep -E '(AB){4}'
  • For what it's worth, -E is specified by POSIX, and grep -E is sometimes available as egrep (although this invocation is now deprecated).
    – rahmu
    Mar 20 '13 at 23:43
  • @rahmu POSIX still doesn't cover the entire range of Unices, and egrep isn't specified by POSIX.
    – Chris Down
    Mar 21 '13 at 0:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.