如何一次存储和删除正则表达式模式?

How to store and remove a regex pattern at once?

我想知道是否可以在不检查正则表达式模式两次的情况下执行此操作。

我在 python 3

pp = re.search(r'(.)(.+)(.+)', word)
word = re.sub(r'(.)(.+)(.+)', '', word)
salv = pp.groups()
word + = salv[0] + salv[0] + inverse(salv[1]) + salv[2]

我首先查找匹配项,然后删除匹配项,但我正在查找相同的正则表达式模式两次。而且我觉得可以用其他方式完成。

所以我想做的是:

匹配一个模式,删除该模式,然后以不同的方式连接我匹配的内容。

您可以将您的正则表达式模式修改为 return 您正在寻找的内容,而无需额外的步骤:

#  here we unpack the object, into the first group and the rest
#   |                  here we match anything else and add to first group
#   v                                  v
word_replacement, *slav = re.search(r'(.*)(.)(.+)(.+)', word)
# now everything is set up the same
word_replacement += slav[0] + slav[0] + inverse(slav[1]) + slav[2]

您还可以将 re.sub 与 \g 标签一起使用:

word_replacement = re.sub('(.)(.+)(.+)', '\g<1>\g<1>\g<2>\g<3>', word)

虽然不确定如何在正则表达式中实现逆

您可以将 re.sub 方法与函数一起用作其 repl 参数的值。

import re
word = 'mmabacbc'
print(re.sub(r'(.)(.+)(.+)', lambda m: m.group(1) * 2 + m.group(2).swapcase() + m.group(3), word))

输出:

mmaaBcbc

使用 Rextester 在线测试。