TAGS :Viewed: 23 - Published at: a few seconds ago

[ python: square backet in character class ]

I'm trying to match square brackets (using character class) in python. But the following code is not successful. Does anybody know what is the correct way to do?

#!/usr/bin/env python

import re
prog = re.compile('[\[]+')
print prog.match('a[f')
prog = re.compile('[\]]+')
print prog.match('a]f')

Answer 1


The issue isn't the square bracket, it's that match (as the docs put it) "[t]r[ies] to apply the pattern at the start of the string". You may want search instead:

>>> prog = re.compile('[\[]+')
>>> print prog.match('a[f')
None
>>> print prog.search('a[f')
<_sre.SRE_Match object at 0xa7a7448>
>>> print prog.search('a[f').group()
[