所选正则表达式组中的正则表达式替换

2024-05-19 22:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下字符串

I only work between September 12 -14 at this place. I will be back between May 10-15 next year.

使用下面的正则表达式,我能够捕获字符串的必需部分,即日期后的下一个月

(\w+\s?)(\d{1,2}\s?)-(\d{1,2})

此正则表达式返回2个完全匹配项

比赛1

  • 全场比赛:9月12日至14日
  • 第一组:9月
  • 第2组:12
  • 第3组:14

比赛2

  • 全场比赛:5月10日至15日
  • 第一组:五月
  • 第2组:10
  • 第3组:15

我想要的是使用正则表达式替换在第3组之前插入第1组。 尽管有其他方法可以考虑,但我找不到使用正则表达式替换的方法

我计划在python中使用它

所需的输出应该如下所示

I only work between September 12 -September 14 at this place. I will be back between May 10-May 15 next year.


Tags: 字符串onlybackplacebebetweenthisyear
1条回答
网友
1楼 · 发布于 2024-05-19 22:25:39

你可以匹配

(\w+) ?(\d{1,2} ?-)(\d{1,2})

并替换为第一组,第二组,再次替换第一组(插入月份),然后替换第三组:

\1 \2\1 \3

https://regex101.com/r/Zcqsr2/1

import re
str = 'I only work between September 12 -14 at this place. I will be back between May 10-15 next year.'
print(re.sub(r'(\w+) ?(\d{1,2} ?-)(\d{1,2})', r'\1 \2\1 \3', str))

相关问题 更多 >