python正则表达式 - 删除re.sub之前的空白

python正则表达式 - 删除re.sub之前的空白

问题描述:

这里是我的代码片断,这是基本的,我知道!我正在开始冒险进入正则表达式。当我运行下面的代码时,一切正常,但我想知道如何缩小连字符和字符串替换之间的差距,例如,它指出了一天的持续时间,例如, “八小时一天”现在写着“八BOOGIE日”,我想关闭这个空间。请帮忙!python正则表达式 - 删除re.sub之前的空白

import re 

short_par = 'You must pace your work. What do I mean? I’m glad you asked that. We pace our work according to the eight-hour workday. If you have twelve hours of work in your in-box, for example, you must compress that work into the eight-hour day. If you have one hour of work in your in-box, you must expand that work to fill the eight- hour day. That was a good question. Feel free to ask questions. Ask too many questions, however, and you may be let go.' 

regex = re.compile('[hy]our') 

print(regex.sub('BOOGIE', short_par)) 
+0

请尊重SO社区并发布MINIMAL示例。整个'long_par'字符串不需要说明你的问题,但我们必须水平滚动才能找到'八小时'的地方。 – DyZ

+0

我想你也可以用're.sub'来做你想做的事情。你应该能够弄清楚。 –

+0

非常有帮助,你们都谢谢你的见解。 –

您可以使用lookbehind

(?:(?<=-))?[hy]our 

的回顾后(?<=-)检查破折号是存在的,但并不匹配。这很重要,因为我们不希望re.sub取代它。

如果发现短划线,则(?:(?<=-))?与之后的空格相匹配,以便它被替换。