选定正则表达式组的正则表达式替换
Regex Substitution from the Selected Regex Group
我有以下字符串
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})
这个正则表达式 returns 2 个完全匹配项
匹配 1
- 全场比赛:9月12日-14日
- 第 1 组:9 月
- 组 2: 12
- 组 3: 14
匹配 2
- 完整比赛:5 月 10-15 日
- 组 1:5 月
- 第 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.
你可以匹配
(\w+) ?(\d{1,2} ?-)(\d{1,2})
并替换为第一组,第二组,再次替换第一组(插入月份),然后是第三组:
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' ', str))
我有以下字符串
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})
这个正则表达式 returns 2 个完全匹配项
匹配 1
- 全场比赛:9月12日-14日
- 第 1 组:9 月
- 组 2: 12
- 组 3: 14
匹配 2
- 完整比赛:5 月 10-15 日
- 组 1:5 月
- 第 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.
你可以匹配
(\w+) ?(\d{1,2} ?-)(\d{1,2})
并替换为第一组,第二组,再次替换第一组(插入月份),然后是第三组:
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' ', str))