如何在Python正则表达式中匹配零个或多个括号
我想要一个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吗?
3 个回答
0
最后,我想做的事情是从一个字符串中去掉方括号或大括号以及它们里面的内容。如果我发现了这些括号,就把它们和里面的内容都删掉。我之前的做法是先找出需要处理的字符串,然后再在第二步中修复它们。其实我只需要一步就能同时完成这两个操作,如下所示:
re.sub ("\[.*\]|\{.*\}", "", one)
2
这是另一种方法。
import re
def ismatch(match):
return '' if match is None else match.group()
one = 'this is the first string [with brackets]'
two = 'this is the second string without brackets'
ismatch(re.search('\[', one)) # Returns the bracket '['
ismatch(re.search('\[', two)) # Returns empty string ''
6
答案很简单!:
(\[+|$)
因为你只需要关注字符串最后的那个空字符串。