[Tutor] search and replace

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Mar 7 19:40:24 CET 2006


> regex allows us to specify certain conditions in the patterns
> such as whether the characters are digits etc, and also whether
> we are kooking for a word which is wat you want.
> Specifically \W signifies a word boundary so
>
> \Whello\W
>
> will find hello as a word.

Hi Alan,


Using the non-word pattern '\W' will work except in cases where we're
right at the edge:

######
>>> import re
>>> re.sub(r'\Whi\W', 'hello', 'hi there')
'hi there'
######


Slightly more robust is the '\b' boundary assertion pattern:

######
>>> re.sub(r'\bhi\b', 'hello', 'hi there')
'hello there'
######


Best of wishes!



More information about the Tutor mailing list