繁体   English   中英

Python正则表达式匹配方括号内的数字列表

[英]Python regular expression to match a list of numbers inside square brackets

因此,我试图做一个从文本返回所有引用(CITS)的函数,有时此文本是一个列表,这就是为什么我首先对其进行验证的原因。

def get_cits_from_note(note):
    if note:
        if isinstance(note, list):
            note = "".join(note)
        matchGroups = re.findall(r'\|CITS\s*:*\s*\[\s*(\d+)', note)
        if matchGroups:
            citsList = [match for match in matchGroups]
            print citsList

文本将是这样的(文本是我从Wikipedia复制/粘贴的东西,这就是为什么它没有任何意义):

括号是一个高标点符号,通常用于文本内的匹配对中| CITS:[123],[456],[789] | 分开或插入其他文字。 最好将匹配对描述为开放和| CITS:[999] |。 在左至右的上下文中,它的形式可能不那么正式,可以描述为左右,在右至左的上下文中,可以描述为左右。

这是我构建的第一个正则表达式:

matchGroups = re.findall(r'\|CITS\s*:*\s*\[\s*(\d+)', note)

但它只会打印:

[u'123']

所以我做了第二个正则表达式:

matchGroups = re.findall(r'\|CITS\s*:*\s*((\[\s*(\d+)]+,*\s*)+)\|', note)

但它不能像我想要的那样导致它打印:

[(u'[123], [456], [789]', u'[789]', u'789'), (u'[999]', u'[999]', u'999')]

我使用这种正则表达式已有一段时间了,我无法使其正常运行,有人可以告诉我我想念的是什么吗?

最终输出应为:

[u'123',u'456',u'789',u'999']
import re
note = "A bracket is a tall punctuation mark typically used in matched pairs within text, |CITS: [123],[456],[789]| to set apart or interject other text. The matched pair is best described as opening and |CITS: [999]|. Less formally, in a left-to-right context, it may be described as left and right, and in a right-to-left context, as right and left."
matchGroups = re.findall(r'\d+', note)
print matchGroups

输出

['123', '456', '789', '999']

不仅仅使用正则表达式,但是如果我正确理解您的目标,可以这样做:

raw_list = [x.strip().split(',')
            for x in re.findall(r'\|CITS\s*:([\[\]\d\s,]+)', note)]
flatten = lambda l : [item for sublist in l for item in sublist]
cits = flatten(raw_list)

但是,这也会匹配“ | CITS:[[1,7 [,””之类的废话的出现。

暂无
暂无

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

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