Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.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,在这个问题之后,如果连字符没有出现在美国邮政编码中,我将尝试替换它 逻辑是: 数字之间不匹配连字符 匹配连字符 我已尝试使用以下方法实现此目标: import re p = re.compile(r'(?!\d+\-\d+)-') # regex here test_str = "12345-4567 hello-you" re.sub(p, " ", test_str) 预期输出:12345-4567您好 实际输出:123454567您好 我做

在这个问题之后,如果连字符没有出现在美国邮政编码中,我将尝试替换它

逻辑是:

  • 数字之间不匹配连字符
  • 匹配连字符
我已尝试使用以下方法实现此目标:

import re
p = re.compile(r'(?!\d+\-\d+)-') # regex here
test_str = "12345-4567 hello-you"
re.sub(p, " ", test_str)
  • 预期输出:
    12345-4567您好
  • 实际输出:
    123454567您好
我做错了什么?

您可以使用

import re
p = re.compile(r'(?!(?<=\d)-\d)-')
test_str = "12345-4567 hello-you 45-year N-45"
print(re.sub(p, " ", test_str))
# => 12345-4567 hello you 45 year N 45
请参阅和

\b(\d{5}-\d{4})\b
首先匹配并捕获组1中的单词边界位置,然后匹配任意五位数字、连字符、四位数字,然后再匹配单词边界。替换模式中的
\1
反向引用是指组1中捕获的值

re.sub(r'\b(\d{5}-\d{4})\b|-', r'\1 ', text)