找到几个带正则表达式的字符串

2024-09-30 03:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个或功能,以匹配几个字符串与正则表达式。你知道吗

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

Tags: ortheto字符串功能refindlike
2条回答

为了匹配hex or mos or sig,应该删除[]元字符。(?:-(hex|mos|sig))

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

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

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

或者您可以使用r'"-(hex|mos|sig)"'r"-\1"作为替换(因为-不再是组的一部分)。你知道吗

相关问题 更多 >

    热门问题