2017-08-04 137 views
-1

這裏是我的代碼片斷,這是基本的,我知道!我正在開始冒險進入正則表達式。當我運行下面的代碼時,一切正常,但我想知道如何縮小連字符和字符串替換之間的差距,例如,它指出了一天的持續時間,例如, 「八小時一天」現在寫着「八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

非常有幫助,你們都謝謝你的見解。 –

回答

1

您可以使用lookbehind

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

的回顧後(?<=-)檢查破折號是存在的,但並不匹配。這很重要,因爲我們不希望re.sub取代它。

如果發現短劃線,則(?:(?<=-))?與之後的空格相匹配,以便它被替換。