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)
4

2 回答 2

1

方括号用于只能匹配单个字符的字符类。如果要匹配多个字符替代项,则需要使用组(括号而不是方括号)。尝试将您的正则表达式更改为以下内容:

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

请注意,我使用了非捕获组(?:...),因为您不需要另一个捕获组,但r'"(-(hex|mos|sig))"'实际上会以相同的方式工作,因为\1除了引号之外仍然是所有内容。

替代方案您可以使用r'"-(hex|mos|sig)"'r"-\1"用作替代品(因为-不再是该组的一部分。

于 2012-06-11T19:32:50.350 回答
0

您应该删除[]元字符以匹配hex or mos or sig.(?:-(hex|mos|sig))

于 2012-06-11T19:32:51.520 回答