tags:

views:

120

answers:

2

Hi! I'm newbie in Python. I can't understand why this code does not work:

reOptions = re.search(
    "[\s+@twitter\s+(?P<login>\w+):(?P<password>.*?)\s+]",
    document_text)
if reOptions:
    login = reOptions.group('login')
    password = reOptions.group('password')

I'm having an error:

IndexError: no such group
With document_text
Blah-blah
[ @twitter va1en0k:somepass ]
+3  A: 

You need to escape the brackets [ and ] as \[ and \].

\[\s+@twitter\s+(?P<login>\w+):(?P<password>.*?)\s+\]
Jeremy Stein
oh, thank you. but why does statements after if execute? how to know if re finded anything?
valya
Well, it's still a regular expression. It just matches any of the literal characters between [ and ]. But the login and password groups don't exist, so you get the error.
Jeremy Stein
+2  A: 

The [ and ] are special regular expression characters. Escape them to match literal [ and ]. See Regular Expression Syntax.

Blair Conrad
oh, thank you. but why does statements after if execute? how to know if re finded anything?
valya
It's' not a matter of the statements being invalid, just that your expression attempts to match things that you didn't mean to - essentially, you're trying to match any of the characters within the [], not the special regular expression constructs you made. You can tell you matched something because reOptions is not None. You can use MatchObject.group with no arguments to see the entire string that was matched.
Blair Conrad