What does "[[]]" mean in regular expression?

What does [[]] mean in regex?

 $ echo '[][]' | grep -oE '[[]]' [] [] $ grep --version grep (GNU grep) 2.10 

Hmm, it seems like it matches [] . (Sequences of characters [] , not [ or ] .) (I tested it with the python re module, the same result.) Really? If so, why?

I knew if I wanted to match [ or ] , I had to write [][] or [[\]] . (They work in PCRE, grep supports [][] , but not [[\]] , since \ loses its special meaning in the grep bracket expression.) I'm only curious.

+4
source share
1 answer

The expression [[]] actually consists of two concatenated subexpressions: [[] and ] .

  • [[] is a character class that matches only characters [ . The presence of [ possible only at the very beginning of the character class.
  • ] is just a normal character if outside the character class.

Both are combined, so your expression matches any character [ followed by ] , which leads to matching [] .

+4
source

Source: https://habr.com/ru/post/1434141/


All Articles