On 15/04/12 08:10, Michael Lewis wrote:
Hi everyone,
I am a bit confused on how one would ever use re.search(). It
essentially tells me the location on (RAM?) if the pattern matches?
No it returns a MatchObject instance.
You can then perform various operations on the
MatchObject to, for example find the substring
which actually matched.
> What is the purpose of this?
So that you can find the section of a long string that
first matches your regex.
Can you give me a good example of where it would
be useful?
Searching for the first occurence of a regex in a long string.
Scan through /string/ looking for a location where the regular
expression /pattern/ produces a match, and return a corresponding
MatchObject
Try reading the docs on MatchObject, here is a simple example:
>>> s = "Here is a string"
>>> m = re.search("is", s)
>>> m
<_sre.SRE_Match object at 0x153b780>
>>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict',
'groups', 'span', 'start']
>>> m.start
<built-in method start of _sre.SRE_Match object at 0x153b780>
>>> m.start()
5
>>> m.end()
7
>>> m.group()
'is'
>>> m.span()
(5, 7)
Hopefully that gives you the basic idea?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor