How does backslash affect curly braces in regex?

Viewed 121

So I started to learn regex using grep and sed in linux, and I don't understand why I have to save curly braces? So saving means escaping characters to match them literally, but when I type in grep 'test{2}' it will only match test{2} and when I type 'test\{2\}' it will match testtest. It's okay, but why backslash has another usage with other modifiers? For example in the case of . (dot), when I type test. it will match any text with test followed by any characters. In this case we need backslash to interpret it as a character. So when I use it like that: test\. it will only match test.

So summarized: why in the case of { backslash saves the curly braces to be interpreted as a character, and in the case of other modifiers, like . backslash saves the character to be interpreted as a special one...

I know it sounds hilarious but I don't understand it...

1 Answers

When grep is used with no -E you need to escape ("save") braces that are quantifiers because the regex flavor used is POSIX BRE:

grep 'test\{2\}' file # => Finds lines having testt, not testtest

and

grep '\(test\)\{2\}' file # => Finds lines having testtest

The identical POSIX ERE variants are

grep -E 'test{2}' file
grep -E '(test){2}' file

Another example is to match curly braces:

grep '{2}' file # => matches lines having {2} in them
grep -E '\{2}' file => same, note the } is not special

See more about BRE and ERE POSIX regex standard.

The differences between BRE and ERE POSIX syntax are just historical, there seems no specific idea behind that.

Related