7koFnMiP
7koFnMiP

Reputation: 477

How to apply methods to capturing groups in re.sub

I want to replace a part of a string using re.sub() however I can't find a way to apply methods to the capturing groups. My code looks like this (bearing in mind that this is just for reproduction and is not my actual problem):

import re

mystring = 'Hello NICE to meet you'
mystring = re.sub('(Hello )(NICE)( to meet you)', r'\1' + r'\2'.lower() + r'\3', mystring)
print(mystring)

>>> Hello NICE to meet you

In the above example, lower() does not affect r'\2', is there any way to get this re.sub to return 'Hello nice to meet you'

Upvotes: 2

Views: 426

Answers (2)

Or Y
Or Y

Reputation: 2118

If you just wanted to capitalize the sentence, you can use str.capitalize:

"hello NICE to meet you".capitalize()
>>> 'Hello nice to meet you'

If you want more than that, and dynamically play with the values of matched regexs:

The re.sub function accepts a handler as the replacement value for the matched regex. the handler should receive one parameter which is of type re.Match.

here is an example that lowercase words:

import re

def handler(match):
    return match.group(1).lower()

re.sub('([A-Za-z]+)', handler, mystring)

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24279

You can use a function instead of a string as replacement. It take the match object as argument, and should return the replaced string, as explained in the documentation for re.sub:

import re

def replace(match):
    return match.group(1) + match.group(2).lower() + match.group(3)


mystring = 'Hello NICE to meet you'
mystring = re.sub('(Hello )(NICE)( to meet you)', replace, mystring)
print(mystring)
# Hello nice to meet you

Upvotes: 3

Related Questions