Skip to main content
 首页 » 编程设计

python之如何将字符串中的连字符 (-) 替换为空格,但字符串中匹配的模式除外

2024年10月01日2352php

我有类似的字符串

text='Studied b-tech from college in 2010-13' 

使用

text.replace('-', ' ') 

会产生

Studied b tech from college in 2010 13 

但我想要的是:

Studied b tech from college in 2010-13 

我已经准备了以下模式来像 2010-13 这样的标记,但我如何在我的代码中使用它?

regex_pattern='(\d{4}-\d{2,4})' 

请您参考如下方法:

您必须使用否定环视描述连字符的两种可能性:

  • 前面没有四位数字:(?<!\b[0-9]{4})
  • 后面没有两位或四位数字:(?![0-9]{2}(?:[0-9]{2})?\b)

( "not preceeded by A or not followed by B" 是 "preceeded by A and followed by B" )

例子:

import re 
 
text = 'Studied b-tech from college in 2010-13' 
 
result = re.sub(r'-(?:(?<!\b[0-9]{4}-)|(?![0-9]{2}(?:[0-9]{2})?\b))', ' ', text) 

demo

(写 - (?: (?<! ... - ) | (?! ... ) ) 比 (?<! ... )-|-(?! ... ) 更有效,这就是为什么你在 lookbehind 中检索连字符)