带lookbehind和lookbeahead的非捕获括号-Python

带lookbehind和lookbeahead的非捕获括号-Python,python,regex,regex-lookarounds,Python,Regex,Regex Lookarounds,所以我想用这样的字符串捕捉索引: "Something bad happened! @ data[u'string_1'][u'string_2']['u2'][0]" 我想捕获字符串string_1,string_2,u2,以及0 我可以使用以下正则表达式执行此操作: re.findall("(" "((?<=\[u')|(?<=\['))" # Begins with [u' or [' "[a-zA-Z0-9_\-]+" # Fo

所以我想用这样的字符串捕捉索引:

 "Something bad happened! @ data[u'string_1'][u'string_2']['u2'][0]"
我想捕获字符串
string_1
string_2
u2
,以及
0

我可以使用以下正则表达式执行此操作:

re.findall("("
           "((?<=\[u')|(?<=\['))" # Begins with [u' or ['
           "[a-zA-Z0-9_\-]+" # Followed by any letters, numbers, _'s, or -'s
           "(?='\])" # Ending with ']
           ")"
           "|" # OR
           "("
           "(?<=\[)" # Begins with [
           "[0-9]+" # Followed by any numbers
           "(?=\])" # Endging with ]
           ")", message)
现在,我可以很容易地从结果中过滤出空字符串,但我想首先防止它们出现

我相信这是因为我的俘虏小组。我试着在那些小组中使用
?:
,但结果完全没有了

我就是这样尝试的:

re.findall("(?:"
           "((?<=\[u')|(?<=\['))" # Begins with [u' or ['
           "[a-zA-Z0-9_\-]+" # Followed by any letters, numbers, _'s, or -'s
           "(?='\])" # Ending with ']
           ")"
           "|" # OR
           "(?:"
           "(?<=\[)" # Begins with [
           "[0-9]+" # Followed by any numbers
           "(?=\])" # Endging with ]
           ")", message)
我假设这个问题是由于我使用lookbehinds和非捕获组造成的。关于在Python中是否可以这样做,有什么想法吗

谢谢

正则表达式:或
\[(?:[^'\]]*')?([^'\]]+)

Python代码

def Years(text):
        return re.findall(r'(?<=\[)(?:[^\'\]]*\')?([^\'\]]+)', text)

print(Years('Something bad happened! @ data[u\'string_1\'][u\'string_2\'][\'u2\'][0]'))

你可以简化你的正则表达式

(?<=\[)u?'?([a-zA-Z0-9_\-]+)(?='?\])

(?这将最终捕获
u'
。我知道你可能会说我可以使用
re.search
并使用
,但是组只捕获子模式的最后一个匹配项。请看这里我的道歉。这很有效。现在我想知道为什么它不捕获
u'
@Mo2 re.findall只提供组I如果它有一个…如果没有那么整个比赛我看到了。直到。谢谢。我不能删除否决票,除非答案被编辑。它不会让我。完成。再次感谢你
def Years(text):
        return re.findall(r'(?<=\[)(?:[^\'\]]*\')?([^\'\]]+)', text)

print(Years('Something bad happened! @ data[u\'string_1\'][u\'string_2\'][\'u2\'][0]'))
['string_1', 'string_2', 'u2', '0']
(?<=\[)u?'?([a-zA-Z0-9_\-]+)(?='?\])