给定这个字符串:
text = "hello world pattern 24 4 5 this is an example pattern 4 3 11 "
我需要用“patternX-Y-Z”替换“pattern X Y Z”,其中 X、Y、Z 是数字(“pattern”和第一个数字之间没有空格)。 到目前为止,我是通过这个正则表达式来做到这一点的:
text= re.sub('pattern\s(\d+)\s(\d+)\s(\d+)', r'pattern\1-\2-\3', text).strip()
假设我有三个以上的组(类似于“模式 12 3 5 7 5 和模式 34 5 4”),其中组的数量不固定且未知先验,我怎么能写我的正则表达式? 有没有一种方法可以编写用于替换的递归正则表达式?
最佳答案
你可以使用
import re
rx = r'(pattern)(\s*[\d\s]*\d)\b'
s = 'hello world pattern 24 4 5 this is an example pattern 4 3 11 6th oct 2018 pattern 4 3 11 124 2'
print(re.sub(rx, lambda x: "{}{}".format(x.group(1), "-".join(x.group(2).split())), s))
# => hello world pattern24-4-5 this is an example pattern4-3-11 6th oct 2018 pattern4-3-11-124-2
参见 Python demo
(pattern)(\s*[\d\s]*\d)\b
匹配
(pattern)
-pattern
到第 1 组(\s*[\d\s]*\d)
-(第 2 组)0+ 个空格,然后是 0+ 个数字和空格,最后是一个数字\b
- 单词边界
替换时,第 1 组的值放在替换的开头,第 2 组的值用空格分隔并用 -
连接回去。
关于python - 替换未知的先验组数 - 正则表达式 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52667072/