Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未知先验组数的替换-正则表达式python_Python_Regex_Recursion - Fatal编程技术网

未知先验组数的替换-正则表达式python

未知先验组数的替换-正则表达式python,python,regex,recursion,Python,Regex,Recursion,给定此字符串: text = "hello world pattern 24 4 5 this is an example pattern 4 3 11 " 我需要用“patternX-Y-Z”替换“patternX-Y-Z”,其中X,Y,Z是数字(“pattern”和第一个数字之间没有空格)。 到目前为止,我通过这个正则表达式: text= re.sub('pattern\s(\d+)\s(\d+)\s(\d+)', r'pattern\1-\2-\3', text).strip() 假设

给定此字符串:

text = "hello world pattern 24 4 5 this is an example pattern 4 3 11 "
我需要用“patternX-Y-Z”替换“patternX-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

(模式)(\s*[\d\s]*\d)\b
匹配

  • (模式)
    -
    模式
    进入第1组
  • (\s*[\d\s]*\d)
    -(第2组)0+个空格,然后是0+个数字和空格,最后是一个数字
  • \b
    -单词边界
替换时,组1的值放在替换的开始处,组2的值用空格分割,并用
-

重新连接。请看一看