Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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 - Fatal编程技术网

Python正则表达式替换为返回匹配

Python正则表达式替换为返回匹配,python,regex,Python,Regex,给定以下字符串 p='12.04.2020 - 17:00 - 13.04.2020 10:00' 如何将第一个破折号(-)替换为空白,这是一个错误 我试过了 re.sub("(20\d*) - (\d*):","\1 \2:",p) '12.04.\x01 \x02:00 - 13.04.2020 10:00' 但它不会返回匹配项 编辑:可能有多个这样的模式,并且该位置可能没有破折号,因此必须明确,我不能只替换找到的第一个破折号。您需要使用r修饰符

给定以下字符串

p='12.04.2020 - 17:00 - 13.04.2020 10:00'
如何将第一个破折号(-)替换为空白,这是一个错误

我试过了

re.sub("(20\d*) - (\d*):","\1 \2:",p)

'12.04.\x01 \x02:00 - 13.04.2020 10:00'
但它不会返回匹配项


编辑:可能有多个这样的模式,并且该位置可能没有破折号,因此必须明确,我不能只替换找到的第一个破折号。

您需要使用
r
修饰符来防止从\d转义到d和\1转义到1

re.sub(r"(20\d*) - (\d*):",r"\1 \2:",p)

你在\上没有匹配。(仅数字\d),并且它只匹配一个破折号。如果您只需要更换看到的第一个破折号,为什么不执行
p.replace('-','',1)
?是否需要验证字符串的格式?
index=p.index(“-”);p=p[:index]+“”+p[index+1:
-不好的做法
p.replace('-','',1)
?@cs95否,因为可能存在多个模式。另外,因为那个地方可能没有破折号,所以代码将替换第二个破折号,这是正确的。您也可以使用
\\d
\\1
r
(又称原始)修饰符前缀更方便。你不需要也解释17:20-13吗?