Python equivalent of Perl e flag with regular expression

George Sakkis george.sakkis at gmail.com
Thu Oct 2 15:00:42 EDT 2008


On Oct 2, 1:06 pm, "Friedman, Jason" <jfried... at oppenheimerfunds.com>
wrote:
> I have lines that look like this:
> select column1, 'select' as type
> from table
> where column2 = 'foo'
>
> I want to return:
> SELECT column1, 'select' AS type
> FROM table
> WHERE column2 = 'foo'
>
> This is SQL with the keywords converted to uppercase.  Note that the
> second "select" string is not a keyword and thus I do not want to
> convert it to uppercase.  Thus, I don't think the string.replace()
> method will work for me.
>
> With Perl I might do something like this:
> $line =~ s/(select)/uc($1)/e;
> More generally:
> for $keyword in (@keyword) {
>   $line =~ s/($keyword)/uc($1)/e;
>
> }

Are you sure that this version returns the desired results ? How does
perl know not to much the keyword within the quotes ?

> How would I do this with Python?

Leaving aside the fact that regexps are not the right tool to check
whether a string is within quotes or not, you can use re.sub() and
pass a callable instead of a replacement string:

>>> import re
>>> keywords = 'select from where as'.split()
>>> regex = re.compile('|'.join(r'\b%s\b' % re.escape(k) for k in keywords), re.I)
>>> sql = """
select column1, 'select' as type
from table
where column2 = 'foo'
"""
>>> print regex.sub(lambda match: match.group().upper(), sql)
SELECT column1, 'SELECT' AS type
FROM table
WHERE column2 = 'foo'

George



More information about the Python-list mailing list