如何应用方法来捕获 re.sub 中的组
How to apply methods to capturing groups in re.sub
我想使用 re.sub()
替换字符串的一部分,但是我找不到将方法应用于捕获组的方法。我的代码看起来像这样(记住这只是为了复制,不是我的实际问题):
import re
mystring = 'Hello NICE to meet you'
mystring = re.sub('(Hello )(NICE)( to meet you)', r'' + r''.lower() + r'', mystring)
print(mystring)
>>> Hello NICE to meet you
上面的例子中,lower()
不影响r''
,请问有什么办法可以让这个re.sub
变成return'Hello nice to meet you'
如果只是想把句子大写,可以使用str.capitalize
:
"hello NICE to meet you".capitalize()
>>> 'Hello nice to meet you'
如果您想要更多,动态地使用匹配的正则表达式的值:
re.sub
函数接受处理程序作为匹配正则表达式的替换值。处理程序应接收一个 re.Match
.
类型的参数
这是一个小写单词的例子:
import re
def handler(match):
return match.group(1).lower()
re.sub('([A-Za-z]+)', handler, mystring)
您可以使用函数代替字符串作为替换。它以匹配对象作为参数,并且应该 return 被替换的字符串,如 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
我想使用 re.sub()
替换字符串的一部分,但是我找不到将方法应用于捕获组的方法。我的代码看起来像这样(记住这只是为了复制,不是我的实际问题):
import re
mystring = 'Hello NICE to meet you'
mystring = re.sub('(Hello )(NICE)( to meet you)', r'' + r''.lower() + r'', mystring)
print(mystring)
>>> Hello NICE to meet you
上面的例子中,lower()
不影响r''
,请问有什么办法可以让这个re.sub
变成return'Hello nice to meet you'
如果只是想把句子大写,可以使用str.capitalize
:
"hello NICE to meet you".capitalize()
>>> 'Hello nice to meet you'
如果您想要更多,动态地使用匹配的正则表达式的值:
re.sub
函数接受处理程序作为匹配正则表达式的替换值。处理程序应接收一个 re.Match
.
这是一个小写单词的例子:
import re
def handler(match):
return match.group(1).lower()
re.sub('([A-Za-z]+)', handler, mystring)
您可以使用函数代替字符串作为替换。它以匹配对象作为参数,并且应该 return 被替换的字符串,如 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