我正在寻找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)
答案 0 :(得分:1)
方括号适用于只能匹配单个字符的字符类。如果要匹配多个字符替代项,则需要使用组(括号而不是方括号)。尝试将正则表达式更改为以下内容:
r'"(-(?:hex|mos|sig))"'
请注意,我使用了非捕获组(?:...)
,因为您不需要其他捕获组,但r'"(-(hex|mos|sig))"'
实际上会以相同的方式工作,因为\1
仍然是一切,但是报价。
备选方案您可以使用r'"-(hex|mos|sig)"'
并使用r"-\1"
作为替换(因为-
不再是该群组的一部分。
答案 1 :(得分:0)
您应该删除[]
元字符以匹配hex or mos or sig
。 (?:-(hex|mos|sig))