我正在寻找一个或功能,以匹配几个字符串与正则表达式。你知道吗
# 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)
为了匹配
hex or mos or sig
,应该删除[]
元字符。(?:-(hex|mos|sig))
方括号用于只能匹配单个字符的字符类。如果您想匹配多个字符,您需要使用一个组(括号而不是方括号)。尝试将正则表达式更改为以下内容:
注意,我使用了一个非捕获组
(?:...)
,因为您不需要另一个捕获组,但是r'"(-(hex|mos|sig))"'
实际上会以相同的方式工作,因为\1
仍然是除引号之外的所有内容。你知道吗或者您可以使用
r'"-(hex|mos|sig)"'
和r"-\1"
作为替换(因为-
不再是组的一部分)。你知道吗相关问题 更多 >
编程相关推荐