[Tutor] regular expressions

arsyed arsyed at gmail.com
Tue Aug 5 13:51:00 CEST 2008


On Tue, Aug 5, 2008 at 7:01 AM, Jim Morcombe <jmorcombe at westnet.com.au> wrote:
> Could someone please give me some help using the "re" module.
>
> This works:
> --------------------------------
> import re
>
> text = "Jim is a good guy"
>
> s2 = re.sub('Jim', 'Fred', text)
> print s2
>
> and I get "Fred is a good guy"
> ---------------------------------
> If I have:
> text = "Bill Smith is nice"
> how do I get rid of "Smith" and just have
> "Bill is nice"
>
> I tried
> s2 = re.sub('Smith', '', text)
> but it complained.
>

What was the error message? It should work fine:

In [25]: text = 'Bill Smith is nice'

In [26]: re.sub('Smith', '', text)
Out[26]: 'Bill  is nice'


> If I have:
> text = "Jim likes a girl (Susan)"
> and I want to get rid of "(Susan)", how do I do this.
>

You need to escape the parentheses because those are grouping
metacharacters in regular expressions:

In [27]: text = 'Jim likes a girl (Susan)'

In [28]: re.sub('\(Susan\)', '', text)
Out[28]: 'Jim likes a girl '


The regex howot document below explains a lot of this stuff:

http://www.amk.ca/python/howto/regex/



> First, the "(" seems to muck things up.
> Second, how do I just use "re" to delete characters.  I tried using "sub",
> but it doesn't seem to like
>
> Jim Morcombe
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list