Hopefully simple regular expression question

Kalle Anke skromta at gmail.com
Tue Jun 14 14:41:51 CEST 2005

On Tue, 14 Jun 2005 13:01:58 +0200, peterbe at gmail.com wrote
(in article <1118746918.581184.5470 at g49g2000cwa.googlegroups.com>):

> How do I modify my regular expression to match on expressions as well
> as just single words??

import re

def createStandaloneWordRegex(word):
    """ return a regular expression that can find 'peter' only if it's
		written alone (next to space, start of string, end of string,
		comma, etc) but not if inside another word like peterbe """

    return re.compile(r'\b' + word + r'\b', re.I)

def test_createStandaloneWordRegex():
    def T(word, text):
        print createStandaloneWordRegex(word).findall(text)

    T("peter", "So Peter Bengtsson wrote this")
    T("peter", "peter")
    T("peter bengtsson", "So Peter Bengtsson wrote this")


More information about the Python-list mailing list