编程语言
首页 > 编程语言> > python – 替换正则表达式中的字符

python – 替换正则表达式中的字符

作者:互联网

使用Python,我有以下字符串:

['taxes.............................       .7        21.4    (6.2)','regulatory and other matters..................$  39.9        61.5        41.1','Producer contract reformation cost recoveries............................   DASH        26.3        28.3']

我需要用空格替换每个点,而不是数字中的句点.所以结果应该是这样的:

['taxes                                    .7        21.4    (6.2)','regulatory and other matters                  $  39.9        61.5        41.1','Producer contract reformation cost recoveries                               DASH        26.3        28.3']

我尝试过以下方法:

dots=re.compile('(\.{2,})(\s*?[\d\(\$]|\s*?DASH|\s*.)')
newlist=[]
for each in list:
    newline=dots.sub(r'\2'.replace('.',' '),each)
    newdoc.append(newline)

但是,此代码不保留空白区域.谢谢!

解决方法:

在re.sub中使用negative lookarounds

>>> import re
>>> s = ['taxes.............................       .7        21.4    (6.2)','regulatory and other matters..................$  39.9        61.5        41.1','Producer contract reformation cost recoveries............................   DASH        26.3        28.3']
>>> [re.sub(r'(?<!\d)\.(?!\d)', ' ', i) for i in s]
['taxes                                    .7        21.4    (6.2)', 'regulatory and other matters                  $  39.9        61.5        41.1', 'Producer contract reformation cost recoveries                               DASH        26.3        28.3']

标签:python,regex,replace,substitution
来源: https://codeday.me/bug/20190611/1220607.html