3 回答

TA貢獻1772條經(jīng)驗 獲得超8個贊
該h
替代匹配h
的heures
和heures?
替代甚至沒有測試。交換替代方案可以解決問題,但是最好使用可選的非捕獲組(請參見下面的解決方案)。
建議不要在模式中的捕獲括號中刪除它們(或者,如果要使用替換,則將其轉(zhuǎn)換為非捕獲組)。
此外,該([0-9]+)?
模式可以簡化為[0-9]*
。
您可以使用
[0-9]+\s?h(?:eures?)?[0-9]*
細節(jié)
[0-9]+
-一個或多個數(shù)字\s?
-1或0個空格h
-h
一封信(?:eures?)?
-與1個或0個匹配項發(fā)生eure
或匹配的可選非捕獲組eures
[0-9]*
-0或更多數(shù)字。
參見Python演示:
import re
text = "I should leave the house at 16h45 but I am late and I should not be arriving between 2 h or 3h or maybe 4heures"
hour = re.compile(r'[0-9]+\s?h(?:eures?)?[0-9]*')
replaces = hour.sub('#hour', text)
print(replaces)
# => I should leave the house at #hour but I am late and I should not be arriving between #hour or #hour or maybe #hour

TA貢獻1821條經(jīng)驗 獲得超5個贊
更改的順序heures
和h
括號,像這里面:
[0-9]+\s?(heures?|h)([0-9]+)?
應該管用。
在情況下(h|heures?)
,你是說,如果h
沒有找到,然后看是否heures
存在。無論何時heures
存在,事物h
都會始終存在(它的第一個字符heures
)。因此,您需要更改順序。您應該先搜索heures
,如果不存在,則搜索h
。因此,替換 (h|heures?)
為即可(heures?|h)
解決問題。

TA貢獻1844條經(jīng)驗 獲得超8個贊
您需要切換交替,因為第一部分中的h首先被匹配。
例如4heures
,您的正則表達式匹配一個或多個數(shù)字\d+
。然后在交替中(h|heures?)
它可以匹配h
from heures
。在替換匹配的4h
將被替換#hour
導致#houreures
import re
text = "I should leave the house at 16h45 but I am late and I should not be arriving between 2 h or 3h or maybe 4heures"
hour = re.compile(r'[0-9]+\s?(heures?|h)([0-9]+)?')
replaces = hour.sub('#hour', text)
print(replaces)
添加回答
舉報