checking a string against multiple patterns

grflanagan grflanagan at yahoo.co.uk
Tue Dec 18 08:19:12 EST 2007


On Dec 18, 1:41 pm, tomasz <tmkm... at googlemail.com> wrote:
> Hi,
>
> here is a piece of pseudo-code (taken from Ruby) that illustrates the
> problem I'd like to solve in Python:
>
> str = 'abc'
> if str =~ /(b)/     # Check if str matches a pattern
>   str = $` + $1    # Perform some action
> elsif str =~ /(a)/ # Check another pattern
>   str = $1 + $'    # Perform some other action
> elsif str =~ /(c)/
>   str = $1
> end
>
> The task is to check a string against a number of different patterns
> (containing groupings).
> For each pattern, different actions need to be taken.
>

In the `re.sub` function (and `sub` method of regex object), the
`repl` parameter can be a callback function as well as a string:

http://docs.python.org/lib/node46.html

Does that help?

Eg.

def multireplace(text, mapping):
    rx = re.compile('|'.join(re.escape(key) for key in mapping))
    def callback(match):
        key = match.group(0)
        repl = mapping[key]
        log.info("Replacing '%s' with '%s'", key, repl)
        return repl
    return rx.subn(callback, text)

(I'm not sure, but I think I adapted this from: http://effbot.org/zone/python-replace.htm)

Gerard



More information about the Python-list mailing list