python中字符串的特殊正则表达式

2024-06-10 16:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根像下面这样的线。你知道吗

s = ({[test1, test2 ; test3 (New) ]})

现在我有一个正则表达式,它将删除方括号并将其转换为列表。即使有也用a分开;b,c像。 正则表达式:

output = [i for i in re.split(r'\s*[(){}<>\[\],;\'"]\s*', s) if i]

但是这个正则表达式也从列表中删除了括号。((新的)在我的情况下)

如何将这个正则表达式应用于字符串的开头和结尾。我知道可以用^来做,但不知道怎么做?你知道吗

预期产量

['test1', 'test2', 'test3 (New)' ]

来自以上正则表达式的输出

['test1', 'test2', 'test3', 'New']

有什么帮助吗?你知道吗


Tags: 字符串inre列表newforoutputif
2条回答
s = '({[test1, test2 ; test3 (New) ]})'

根据你下面的评论,我假设整个字符串的开始方括号的数目等于结束方括号的数目。你知道吗

因此,移除外支架首先需要知道它们的编号:

m = re.match('[({[]*', s)
n_brckt = m.span()[1] - m.span()[0]

然后拆下外支架(-取决于是否发现任何…):

if n_brckt > 0:
    s = s[n_brckt:-n_brckt]
s = s.strip()

In: s
Out: 'test1, test2 ; test3 (New)'

然后,可以在出现逗号或冒号时进行拆分,也可以选择后跟空格:

In: re.split('[,;]+ *', s)
Out: ['test1', 'test2', 'test3 (New)']

使用re.search

import re
s = "({[test1, test2 ; test3 (New) ]})"
m = re.search("\[(.*?)\]", s)
if m:
    #print(m.group(1).replace(";", ",").split(",")) 
    print([i.strip() for i in m.group(1).replace(";", ",").split(",")])

输出:

['test1', 'test2', 'test3 (New)']

相关问题 更多 >