Python version of a Perl regular expression
Question: I have this Perl regular expression and I want to convert it to Python.

The regex I want is a search and replace that finds text and converts it to
upper case. It also must be the first occurring result. Perl regex:

    
    
    open FILE, "C:/thefile.txt";
    while (<FILE>){
        # Converts "foo yadayada bar yadayada"
        #       to "FOO  bar yadayada"
        s/(^.*?)(yadayada)/\U$1/;
        print;
    }
    

The Python regex I have is not working correctly:

    
    
    import re
    lines = open('C:\thefile.txt','r').readlines()
    for line in lines:
        line = re.sub(r"(yadayada)","\U\g<1>", line, 1)
        print line
    

I realize the `\U\g<1>` is what isn't working because Python doesn't support
`\U` for uppercase.. so what do I use!?!


Answer: `re.sub` can take a function, which processes each match object and returns a
string. So you can do it like this:

    
    
    In [4]: def uppergrp(match):
       ...:     return match.group(1).upper()
       ...: 
    
    In [5]: re.sub("(yada)", uppergrp, "abcyadadef", count=1)
    Out[5]: 'abcYADAdef'
    

Working with regexes in Python is less convenient, but Python programmers tend
to be less keen to use regexes than Perl coders.

