Python正则表达式后置交换组

问题描述 投票:1回答:1

我正在练习re模块,遇到了一个有趣的问题。

我可以轻易地替换两个词:

re.sub("30 apples", r"apples 30", 'Look 30 apples.') # 'Look apples 30.'

但是,只有当苹果出现30时,我才想换掉这两个词。

这该怎么做?

我试着看后面的方法: re.sub('(?<=\d\d) apples', r'\2 \1', 'Look 30 apples.')

但它不需要群组\ 1和\ 2。

python regex lookbehind
1个回答
2
投票

当你使用(?<=\d\d) apples模式时,匹配在2位数之后开始,是一个空格加上apples。如果您尝试交换这两个值,则需要同时使用这两个值,并且如您所见,lookbehind不会消耗文本。

因此,您需要在模式中使用捕获组,并替换为相应的反向引用:

result = re.sub(r"(\d+)(\s+)(apples)", r"\3\2\1", 'Look 30 apples.')

regex demoRegulex graph

enter image description here

细节

  • (\d+) - 捕获组1(替换模式中的\1):一个或多个数字
  • (\s+) - 捕获第2组(替换模式中的\2):一个或多个空格
  • (apples) - 捕获第3组(替换模式中的\3):apples

Python demo

import re
result = re.sub(r"(\d+)(\s+)(apples)", r"\3\2\1", "Look 30 apples.")
print(result)
© www.soinside.com 2019 - 2024. All rights reserved.