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)