为什么在我的re.split()结果中有空格结果



我想提取括号中的字符串和给定字符串中的单引号,例如given[this'],提取this。但以下示例和结果一直困扰着我:

import re 
target_string = "['this']['current']"
result = re.split(r'[[|]|']+', target_string)
print(result)

我有

['', 'this', 'current', '']
# I expect ['this', 'current']

现在我真的不明白结果中的第一个和最后一个''来自哪里,我保证输入target_string没有这样的前导和尾随空间,我不希望它们出现在结果中

有人能帮我修一下吗?

每次找到模式时使用re.split匹配,并且由于字符串以模式开始和结束,因此在开始和结束时输出'',以便能够在输出中使用join并形成原始字符串

如果你想捕获,为什么不使用re.findall而不是re.split?如果每个括号只有一个单词,则使用非常简单。

target_string = "['this']['current']"
re.findall("w", target_string)

输出

['this', 'current'] 

注意以上内容不适用于

['this is the', 'current']

对于这种情况,您可以使用先行(?=...)和后向(?<=...),并以非自由的方式捕获所有内容.+?

target_string = "['this is the', 'current']"
re.findall("(?<=[').+?(?='])", target_string) # this patter is equivalent "['(.+)']"

输出:

['this is the', 'current']

最新更新