[Tutor] Regexes -- \b ; re.sub

Ibraheem Umaru-Mohammed iumarumo@eidosnet.co.uk
Sun Nov 17 08:28:13 2002


* John Abbe <johnca@ourpla.net> [2002-11-16 09:14]:
> Can someone explain to me why this...
> 
> import re
> matches = re.search (re.compile ("(.)\b(.)"), "spam and eggs are yummy")
> if matches:
>    print matches.groups()
> else:
>    print "no match"
> 
> ...prints out "no match", and this...
> 
> print re.sub (re.compile ("(i)"), "o\1o", "i like eggs and spam")
> 
> ...prints out "oo looke eggs and spam" -- shouldn't it be "oio loioke 
> eggs and spam", after all this...
> 
> print re.search (re.compile ("(i)"), "i like eggs and spam").group(1)
> 
> ...prints out "i"
> 

ibz@ignoramus:$ ipython
Python 2.2.1 (#1, Aug 30 2002, 12:15:30)
Type "copyright", "credits" or "license" for more information.

IPython 0.2.14pre33 -- An enhanced Interactive Python.
?       -> Introduction to IPython's features.
@magic  -> Information about IPython's 'magic' @ functions.
help    -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import re

In [2]: re.compile("(.)\b(.)").search("spam and eggs are yummy")

In [3]: re.compile(r"(.)\b(.)").search("spam and eggs are yummy")
Out[3]: <_sre.SRE_Match object at 0x82c4720>

In [4]: re.compile(r"(.)\b(.)").search("spam and eggs are yummy").groups()
Out[4]: ('m', ' ')

In [5]: re.compile("(i)").sub("o\1o", "i like eggs and spam")
Out[5]: 'o\x01o lo\x01oke eggs and spam'

In [6]: re.compile("(i)").sub(r"o\1o", "i like eggs and spam")
Out[6]: 'oio loioke eggs and spam'

In [7]: re.compile("(i)").search("i like eggs and spam").group(1)
Out[7]: 'i'

In [8]:
ibz@ignoramus:$

> Mucho thanks...Life,
> John

Read the following:

,---- [ "The backslash plague" ]
| http://py-howto.sourceforge.net/regex/node8.html
`----

HTH,

			--ibz.