Python 用正则表达式查找多个字符串
我正在寻找一个或功能,以匹配几个字符串与正则表达式Python 用正则表达式查找多个字符串,python,regex,Python,Regex,我正在寻找一个或功能,以匹配几个字符串与正则表达式 # 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 somethin
# 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)
方括号用于只能匹配单个字符的字符类。如果要匹配多个字符备选方案,则需要使用组(括号而不是方括号)。尝试将正则表达式更改为以下内容:
r'"(-(?:hex|mos|sig))"'
请注意,我使用了一个非捕获组(?:…)
,因为您不需要另一个捕获组,但是r'((hex | mos | sig))“
实际上会以同样的方式工作,因为\1
仍然是除了引号以外的所有内容
或者,您可以使用
r'-(hex | mos | sig)“
并使用r“-\1”
作为替换(因为-
不再是组的一部分。方括号用于只能匹配单个字符的字符类。如果要匹配多个字符替换项,则需要使用组(括号而不是方括号)。请尝试将正则表达式更改为以下内容:
r'"(-(?:hex|mos|sig))"'
请注意,我使用了一个非捕获组(?:…)
,因为您不需要另一个捕获组,但是r'((hex | mos | sig))“
实际上会以同样的方式工作,因为\1
仍然是除了引号以外的所有内容
或者,您可以使用
r'-(hex | mos | sig)
并使用r“-\1”
作为替换(因为-
不再是组的一部分。您应该删除[]
元字符,以便匹配hex或mos或sig
(?:-(hex | mos sig))/code><
元字符以匹配十六进制或mos或sig
(?:-(十六进制)mos | sig))
?:
在组的开头表示组未被捕获。因此,在替换中您将无法引用\2
,因为(?:十六进制| mos sig)
表示“匹配hex
、mos
或sig
,但不要将匹配保存到捕获组中”。感谢您的快速响应。您的解释非常有用。?:
在组的开头表示该组未捕获。因此您将无法在替换中引用\2
,因为(?:hex | mos | sig)
表示“匹配hex
、mos
或sig
,但不要将匹配保存到捕获组”。感谢您的快速响应。您的解释非常有用。