2015-10-13 48 views
6

我想使用正則表達式替換出現在空格之間的破折號。例如,要用ab cd替換ab-cd如何使用正則表達式替換字符之間的空格使用正則表達式

以下內容與字符字符序列匹配,但也會替換字符[即ab-cd結果a d,而不是作爲ab cd我渴望]

new_term = re.sub(r"[A-z]\-[A-z]", " ", original_term) 

如何適應我上面只更換-一部分?

+0

鈣ñ你通過簡單地用給定字符串中的空格替換'-'來做到這一點?使用正則表達式是必要的嗎? –

+1

@JeffBridgman是的 - 我只想在字符之間出現破折號而不是在空格之間進行替換。即替換'ab-cd',但不要改變'ab-cd' - ['replace'沒有這個控制]。 – kyrenia

回答

6

你需要和之前捕捉到人物-一組後,並用它們替換,即:

import re 
subject = "ab-cd" 
subject = re.sub(r"([a-z])\-([a-z])", r"\1 \2", subject , 0, re.IGNORECASE) 
print subject 
#ab cd 

DEMO

http://ideone.com/LAYQWT


REGEX說明

([A-z])\-([A-z]) 

Match the regex below and capture its match into backreference number 1 «([A-z])» 
    Match a single character in the range between 「A」 and 「z」 «[A-z]» 
Match the character 「-」 literally «\-» 
Match the regex below and capture its match into backreference number 2 «([A-z])» 
    Match a single character in the range between 「A」 and 「z」 «[A-z]» 

\1 \2 

Insert the text that was last matched by capturing group number 1 «\1» 
Insert the character 「 」 literally « » 
Insert the text that was last matched by capturing group number 2 «\2» 
6

使用引用捕獲組:

>>> original_term = 'ab-cd' 
>>> re.sub(r"([A-z])\-([A-z])", r"\1 \2", original_term) 
'ab cd' 

這是假設,當然,你不能只是出於某種原因做original_term.replace('-', ' ')。也許你的文本使用連字符,它應該使用破折號或其他東西。

+0

由於正則表達式使用ascii表索引,所以不應該使用'[A-z]'。對於此特定範圍,您將匹配'A-Z [\]^_ \'a-z'。然而,如果你想使用'a-z'作爲關鍵字不敏感的話,你可以使用'(?i)'。例如,你可以有'(?i)([a-z])\ - ([a-z])'。無論如何,我知道OP的原始正則表達式是......但只是說。 –

1

您需要使用查找變通:

new_term = re.sub(r"(?i)(?<=[A-Z])-(?=[A-Z])", " ", original_term) 

或捕獲組:

new_term = re.sub(r"(?i)([A-Z])-([A-Z])", r"\1 \2", original_term) 

IDEONE demo

注意[A-z]也符合一些非字母(即[\],^,_`),因此,我建議用[A-Z]替換它,並使用不區分大小寫的修飾符(?i)

請注意,您不必在字符類外部轉義連字符。

2

re.sub()總是用替換替換整個匹配序列。

解決方案只取代短劃線是看起來看起來後面斷言。他們不計入匹配的序列。

new_term = re.sub(r"(?<=[A-z])\-(?=[A-z])", " ", original_term) 

語法在Python documentation for the re module中解釋。

相關問題