Python用函数输出替换字符串模式

nat*_*ill 52 python regex

我说Python中有一个字符串 The quick @red fox jumps over the @lame brown dog.

我试图用一个@以单词作为参数的函数的输出替换每个开头的单词.

def my_replace(match):
    return match + str(match.index('e'))

#Psuedo-code

string = "The quick @red fox jumps over the @lame brown dog."
string.replace('@%match', my_replace(match))

# Result
"The quick @red2 fox jumps over the @lame4 brown dog."
Run Code Online (Sandbox Code Playgroud)

有一个聪明的方法来做到这一点?

Jan*_*ila 91

你可以传递一个函数re.sub.该函数将接收匹配对象作为参数,用于.group()将匹配作为字符串提取.

>>> def my_replace(match):
...     match = match.group()
...     return match + str(match.index('e'))
...
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'
Run Code Online (Sandbox Code Playgroud)

  • 美丽.我不知道我可以将函数传递给re.sub,但我觉得我应该能够. (5认同)

Dav*_*L17 6

我不知道你可以将功能传递给re.sub()任何一个.重复@Janne Karila解决我遇到的问题的答案,该方法也适用于多个捕获组.

import re

def my_replace(match):
    match1 = match.group(1)
    match2 = match.group(2)
    match2 = match2.replace('@', '')
    return u"{0:0.{1}f}".format(float(match1), int(match2))

string = 'The first number is 14.2@1, and the second number is 50.6@4.'
result = re.sub(r'([0-9]+.[0-9]+)(@[0-9]+)', my_replace, string)

print(result)
Run Code Online (Sandbox Code Playgroud)

输出:

The first number is 14.2, and the second number is 50.6000.

这个简单的示例需要存在所有捕获组(没有可选组).


小智 5

尝试:

import re

match = re.compile(r"@\w+")
items = re.findall(match, string)
for item in items:
    string = string.replace(item, my_replace(item)
Run Code Online (Sandbox Code Playgroud)

这将允许您将任何以 @ 开头的内容替换为函数的输出内容。我不是很清楚您是否也需要该功能的帮助。如果是这种情况,请告诉我