我需要一个Python正则表达式来捕获括号或空字符串。尝试通常的方法不起作用。我需要在某个地方转义一些东西,但是我已经尝试了我知道的所有方法。
one = "this is the first string [with brackets]"
two = "this is the second string without brackets"
# This captures the bracket on the first but throws
# an exception on the second because no group(1) was captured
re.search('(\[)', one).group(1)
re.search('(\[)', two).group(1)
# Adding a "?" for match zero or one occurrence ends up capturing an
# empty string on both
re.search('(\[?)', one).group(1)
re.search('(\[?)', two).group(1)
# Also tried this but same behavior
re.search('([[])', one).group(1)
re.search('([[])', two).group(1)
# This one replicates the first solution's behavior
re.search("(\[+?)", one).group(1) # captures the bracket
re.search("(\[+?)", two).group(1) # throws exception
我需要检查搜索结果是否返回了None,这是唯一的解决方案吗?
\[
是否匹配即可。如果捕获组只能匹配单个字符[
,那么它的目的是什么呢? - donfuxxcontent
]? - zx81