Andrew Stevens
Andrew Stevens

Reputation: 41

how to pass a match object from re.sub as an argument

I'm using re.sub to look for a pattern and replace the matches, with the replacement being conditional based on the match. How do I pass the match as an argument? python-3.7

I've successfully passed 'match' if I use the following:

string = re.sub(r"{(.*?)}", replaceVar, string)

But this method doesn't allow me to pass additional arguments, which is what I need to do.

import re

def matchVar(match, another_argument):
    if match.group(1) == another_argument:
        return f'{{{another_argument}}}'
    else:
        return f'{{{another_argument}[{match.group(1)}]}}'

def replaceVar(string, another_argument):
    string = re.sub(r"{(.*?)}", matchVar(match, another_argument), string)
    return string

string = 'This is a {x} sentence. This is another {y} sentence.'
another_argument = 'x'
string = replaceVar(string, another_argument)
print(string)

The string should result in

'This is a {x} sentence. This is another {x[y]} sentence.'

But instead I'm receiving an error 'NameError: name 'match' is not defined'.

(I understand 'match' isn't defined. I'm not sure how to define 'match'.)

How do I pass 'match' as an argument? Thanks!

Upvotes: 1

Views: 1308

Answers (1)

Smart Manoj
Smart Manoj

Reputation: 5844

You have to use lambda and pass the match

string = re.sub(r"{(.*?)}", lambda match :matchVar(match, another_argument), string)

Or change the matchVar to def matchVar(match): and pass the function like re.sub(r"{(.*?)}", matchVar, string)

Upvotes: 3

Related Questions