Python如何用正则删除数字与非数字字符间的连字符
解决方案
方案1:使用零宽断言直接匹配目标连字符
这是最简洁的实现方式,正则仅匹配符合规则的连字符本身,不会触碰前后的字符,直接替换为空即可:
正则规则:(?<=\d)-(?=\D)|(?<=\D)-(?=\d)
(?<=\d)-(?=\D):匹配前面是数字、后面是非数字的连字符(?<=\D)-(?=\d):匹配前面是非数字、后面是数字的连字符
代码示例:
import re def remove_specified_hyphen(s: str) -> str: pattern = r'(?<=\d)-(?=\D)|(?<=\D)-(?=\d)' return re.sub(pattern, '', s) # 测试用例 print(remove_specified_hyphen('2-f')) # 输出 2f print(remove_specified_hyphen('f-2')) # 输出 f2 print(remove_specified_hyphen('a-b')) # 输出 a-b(非数字和非数字之间的连字符保留) print(remove_specified_hyphen('3-4')) # 输出 3-4(数字和数字之间的连字符保留)
方案2:使用替换回调函数(适用于更复杂的匹配场景)
如果后续匹配规则可能扩展,可以用re.sub的回调参数处理匹配结果,直接把匹配到的片段里的连字符删掉即可:
代码示例:
import re def remove_specified_hyphen(s: str) -> str: pattern = r'\d-\D|\D-\d' return re.sub(pattern, lambda match: match.group(0).replace('-', ''), s)
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

