2

Why in python if we use 2 bracket within character class without escape them if match [] but not ] or [ :

>>> re.search(r'[[]]','[]').group()
'[]'
>>> re.search(r'[[]]','[').group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

But if we escape them it will work as expected :

>>> re.search(r'[\[\]]','[').group()
'['
>>> re.search(r'[\[\]]',']').group()
']'
4
  • 1
    once the regex engine finds ], it consider this as a the end of char class. So we have ([[] = [) + (] = ]) which inturn matches [] but fails to match [ because it expects another ] Commented Apr 30, 2015 at 17:14
  • @AvinashRaj Yes, i think that its the reason! Commented Apr 30, 2015 at 17:18
  • Note that you can use this trick to define a character class with the two brackets without any escape: [][] (it works because empty character class is not allowed and the first closing bracket is seen as a literal character) Commented Apr 30, 2015 at 17:49
  • @CasimiretHippolyte Yeah! Commented Apr 30, 2015 at 17:51

1 Answer 1

3

An opening bracket [ starts a new character class, whose scope ends as soon as it encounters the first closing bracket - ].

Now, consider your regex:

[[]]

The scope of character class started by first [, ends at 3rd position. So, the regex is nothing but, [ (as in character class) followed by ] (The last character). So, clearly it won't match a [.

But, as soon as you escape the first ], it loses its behaviour of closing the character class. So, in the below regex:

[[\]]

the character class gets closed only by the last ]. So, the regex would match either [, or ].

Note: There isn't any need to escape [ inside a character class, as it doesn't have a special behaviour there. It can't start a new character class inside a character class, also, it can't close the existing character class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.