[Tutor] Regular expressions

Peter Otten __peter__ at web.de
Thu Feb 13 08:24:28 CET 2014


Santosh Kumar wrote:

> Hi all,
> 
> I am using ipython.
> 
> 1 ) Defined a string.
> 
> In [88]: print string
> foo foobar
> 
> 2) compiled the string to grab the "foo" word.
> 
> In [89]: reg = re.compile("foo",re.IGNORECASE)
> 
> 3) Now i am trying to match .
> 
> In [90]: match = reg.match(string)
> 
> 4) Now i print it.
> 
> In [93]: print match.group()
> foo
> 
> Correct me if i am wrong, i am expecting both "foo" and "foobar", why is
> it giving
> just "foo"

re.match always gives at most one match, and that match has to start at the 
beginning of the string:

>>> import re
>>> r = re.compile("foo", re.I)
>>> help(r.match)
Help on built-in function match:

match(...)
    match(string[, pos[, endpos]]) --> match object or None.
    Matches zero or more characters at the beginning of the string

>>> r.match("bar foobar")
>>>

Use re.findall() if you need all matches

>>> r.findall("foo FOObar")
['foo', 'FOO']

or re.finditer() if you need other information than just the matching 
string:

>>> [m.start() for m in r.finditer("foo FOObar")]
[0, 4]




More information about the Tutor mailing list