On Wed, Jan 18, 2012 at 9:53 AM, Chris Kavanagh <[email protected]> wrote:
> Hey guys, girls, hope everyone is doing well.
>
> Here's my question, when using Regular Expressions, the docs say when using
> parenthesis, it "captures" the data. This has got me confused (doesn't take
> much), can someone explain this to me, please??
>
> Here's an example to use. It's kinda long, so, if you'd rather provide your
> own shorter ex, that'd be fine. Thanks for any help as always.
>
"Capturing" means that the part of the string that was matched is
remembered, so you can extract parts of a string. Here's a small
example that extracts the name and value part of a name=value style
string. Note the use of parentheses, and the calls to the "group"
method of the match object.
the_string = 'A=B'
pair_re = re.compile("""^ # starting from the start of the string
([^=]*) # sequence of characters not containing equals
= # the literal equals sign
(.*) # everything until...
$ # end of string
""", re.VERBOSE)
match_obj = pair_re.match(the_string)
print('Captured name was {}'.format(match_obj.group(1)))
print('Captured value was {}'.format(match_obj.group(2)))
--
regards,
kushal
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor