如何在Python正则表达式中匹配零个或多个括号

5
我需要一个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,这是唯一的解决方案吗?


1
我认为你不需要捕获组。只需查看\[是否匹配即可。如果捕获组只能匹配单个字符[,那么它的目的是什么呢? - donfuxx
不确定问题出在哪里。您想匹配括号或空字符串。第二个输入在每个字符之间包含一个空字符串,因此它匹配空字符串。 - Barmar
通常,正则表达式中的可选项只有在它们前面或后面有其他你想匹配的内容时才有意义。单独搜索它是没有意义的——如果它是可选的,输入将匹配无论它是否包含它。 - Barmar
你是不是在说返回括号中的 [content]? - zx81
3个回答

6
答案很简单! :
(\[+|$)

因为您需要捕获的唯一空字符串是字符串的最后一个。

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  ''

0

最终,我想要做的是将一个字符串中的方括号或花括号及其内容去除。

一开始,我尝试通过查找匹配项并在第二步修复生成的列表来先确定需要修复的字符串,但实际上我只需要同时进行两者即可,具体操作如下:

re.sub ("\[.*\]|\{.*\}", "", one)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接