two ideoms at one blow: line-reading and regexp-matching

Carel Fellinger cfelling at iae.nl
Wed Feb 20 20:31:48 CET 2002


Russell Nelson <nelson at crynwr.com> wrote:
...
>     if matched = re.match(r'egexp(.*)', line):
>         print matched.group(1)

If you are in need of something like this, you could consider wrapping
it up in an assignable-self-returning var, like:

    >>> class Var:
    ...     def assign(self, value):
    ...         self.value = value
    ...         return self.value
    ... 
    >>> import re
    >>> var = Var()
    >>> if var.assign(re.findall("spam", "spam and spam")):
    >>>     print var.value
    ...
    ['spam', 'spam']

And for further fun you could sugar it up, like:

    >>> class CleverVar(Var):
    ...	    def __getattr__(self, attr):
    ...	        return getattr(self.value, attr)
    ...
    >>> var = CleverVar()
    >>> if var.assign(re.match("(spam)", "spam and spam")):
    ...     print matched.groups()
    ('spam',)
-- 
groetjes, carel



More information about the Python-list mailing list