繁体   English   中英

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

[英]How do I match zero or more brackets in python regex

我想要一个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

是我唯一的解决方案,检查搜索返回无?

答案很简单!

(\[+|$)

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

这是一种不同的方法。

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

最终,我想要做的是取一个字符串,如果我找到任何方括号或大括号,从字符串中删除括号及其内容。 我试图通过查找匹配来确定需要先修复的字符串,然后在第二步中修复结果列表,而我需要做的就是同时执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM