3 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
該h
替代匹配h
的heures
和heures?
替代甚至沒有測(cè)試。交換替代方案可以解決問題,但是最好使用可選的非捕獲組(請(qǐng)參見下面的解決方案)。
建議不要在模式中的捕獲括號(hào)中刪除它們(或者,如果要使用替換,則將其轉(zhuǎn)換為非捕獲組)。
此外,該([0-9]+)?
模式可以簡(jiǎn)化為[0-9]*
。
您可以使用
[0-9]+\s?h(?:eures?)?[0-9]*
細(xì)節(jié)
[0-9]+
-一個(gè)或多個(gè)數(shù)字\s?
-1或0個(gè)空格h
-h
一封信(?:eures?)?
-與1個(gè)或0個(gè)匹配項(xiàng)發(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貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
更改的順序heures
和h
括號(hào),像這里面:
[0-9]+\s?(heures?|h)([0-9]+)?
應(yīng)該管用。
在情況下(h|heures?)
,你是說,如果h
沒有找到,然后看是否heures
存在。無論何時(shí)heures
存在,事物h
都會(huì)始終存在(它的第一個(gè)字符heures
)。因此,您需要更改順序。您應(yīng)該先搜索heures
,如果不存在,則搜索h
。因此,替換 (h|heures?)
為即可(heures?|h)
解決問題。

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
您需要切換交替,因?yàn)榈谝徊糠种械膆首先被匹配。
例如4heures
,您的正則表達(dá)式匹配一個(gè)或多個(gè)數(shù)字\d+
。然后在交替中(h|heures?)
它可以匹配h
from heures
。在替換匹配的4h
將被替換#hour
導(dǎo)致#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)
添加回答
舉報(bào)