我想要一个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
对我来说,唯一的解决办法就是检查搜索是否没有返回任何结果?在