[Tutor] Regular expressions

Walter Prins wprins at gmail.com
Thu Feb 13 18:17:00 CET 2014


Hi,

On 13 February 2014 06:44, Santosh Kumar <rhce.san at gmail.com> wrote:
> 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"

A small addition to Peter's already comprehensive reply: Your regular
expression is not including what follows "foo", it is defined as
*only* the string literal "foo", so it can only ever match and return
the literal string "foo".

Try specifying "foo.*" as the regular expression.  Example session:

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 1.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

[C:/Src]|1> s='foo foobar'

[C:/Src]|2> import re

[C:/Src]|3> reg=re.compile('foo.*', re.IGNORECASE)

[C:/Src]|4> match=reg.match(s)

[C:/Src]|5> print match.group()
foo foobar



Walter


More information about the Tutor mailing list