Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does re.compile(r'[[]]') match?

Tags:

python

regex

With Python's re module, why do the following act differently:

>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
like image 789
gray Avatar asked Dec 01 '22 12:12

gray


1 Answers

The regular expression "[[]]" matches the substring "[]". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is "any of the characters in "[", followed by a "]".

like image 127
Kieron Avatar answered Dec 05 '22 06:12

Kieron