user1399782
user1399782

Reputation: 37

Python version of a Perl regular expression

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!?!

Upvotes: 2

Views: 186

Answers (2)

Dunes
Dunes

Reputation: 40713

The second argument to sub can also be a function, meaning if regex language in python cannot accomplish what you want (or at least makes it very difficult) you can just define your own function to use instead.

eg.

re.sub(pattern, lambda x: x.group(1).upper(), string)

edit: The function gets passed a MatchObject

Upvotes: 2

Thomas K
Thomas K

Reputation: 40340

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.

Upvotes: 3

Related Questions