2012-06-11 41 views
1

我正在尋找一個OR能力來匹配正則表達式的幾個字符串。查找幾個正則表達式的字符串

# I would like to find either "-hex", "-mos", or "-sig" 
# the result would be -hex, -mos, or -sig 
# You see I want to get rid of the double quotes around these three strings. 
# Other double quoting is OK. 
# I'd like something like. 
messWithCommandArgs = ' -o {} "-sig" "-r" "-sip" ' 
messWithCommandArgs = re.sub(
      r'"(-[hex|mos|sig])"', 
      r"\1", 
      messWithCommandArgs) 

這工作:

messWithCommandArgs = re.sub(
      r'"(-sig)"', 
      r"\1", 
      messWithCommandArgs) 

回答

1

方括號是字符類只能匹配單個字符。如果你想匹配多個字符的替代品,你需要使用一個組(括號而不是方括號)。試着改變你的正則表達式如下:

r'"(-(?:hex|mos|sig))"' 

請注意,我用了一個非捕獲組(?:...)因爲你並不需要另一個捕獲組,但r'"(-(hex|mos|sig))"'實際上相同的方式工作,因爲\1仍然是一切,但報價。

替代你可以使用r'"-(hex|mos|sig)"',並使用r"-\1"作爲替換(因爲-不再是集團的一部分。

+0

感謝什麼是否意味着? – historystamp

+0

'?:'在組開始時意味着該組未被捕獲,因此您將無法在替換中引用'\ 2',因爲'(?:hex | mos | sig )'意味着'匹配'hex','mos'或'sig',但不要將匹配保存到捕獲組中。「 –

+0

感謝您的快速r esponse。你的解釋非常有幫助。 – historystamp

0

您應該刪除,以配合hex or mos or sig[]元字符。(?:-(hex|mos|sig))

+0

感謝您的發佈。 – historystamp

相關問題