这是我的代码片段,这是基本的,我知道!我开始冒险进入正则表达式了。当我运行下面的内容时,一切正常,但我想知道如何缩小连字符和字符串替换之间的间隙,例如,如果它指出一天的持续时间,例如“8小时工作日”现在写着“8-BOOGIE日”,我想关闭那个空间。请帮忙!
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 :(得分:1)
您可以使用lookbehind:
(?:(?<=-) )?[hy]our
lookbehind (?<=-)
检查是否存在破折号但与之不匹配。这很重要,因为我们不希望re.sub
替换它。
如果找到破折号,(?:(?<=-) )?
匹配后面的空格,以便它被替换。