0

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')
user1424739
  • 11,937
  • 17
  • 63
  • 152

1 Answers1

2

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()
[
DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    You may also want to get in the habit of using raw string literals to create your patterns - `r'[\[]+'`. It doesn't matter in this instance, but if your backslash is followed by something Python recognizes as an escape sequence your regexp won't work as you expect. The escape sequences are documented here: http://docs.python.org/2.7/reference/lexical_analysis.html#string-literals Such escape sequences are not interpreted in a raw string. – Peter DeGlopper Nov 30 '13 at 03:39