首页 > 解决方案 > 编写一个函数以使用正则表达式从字符串中提取整数

问题描述

尝试编写函数 integers_in_brackets 从给定的字符串中找到所有括在括号中的整数。

示例运行:integers_in_brackets(" afd [asd] [12 ] [a34] [ -43 ]tt [+12]xxx")返回[12, -43, 12]。所以数字和括号之间可以有空格,但除了构成整数的字符之外没有其他字符。

到目前为止,我的进展是:

def integers_in_brackets(s):
    r= []
    patt = re.compile(r'\W\s*(-?\d+)')
    for i in patt.findall(s):
        r.append(int(i))
    return r

然而我似乎在 TMC 中失败了,我只达到了要求的 66%

Failed: test.test_integers_in_brackets.IntegersInBrackets.test_second
        Lists differ: [128, 47, -43, 12] != [47, 12]

First differing element 0:
128
47

First list contains 2 additional elements.
First extra element 2:
-43

- [128, 47, -43, 12]
+ [47, 12] : Incorrect result for string   afd [128+] [47 ] [a34]  [ +-43 ]tt [+12]xxx!

Test results: 2/3 tests passed
 66%[????????????????????????????????????????????????????????????????]

标签: pythonregex

解决方案


这应该有效:

import re
pat=r"(?:\[(\s*?[-+]?\d+\s*?)\])"
list(map(eval, re.findall(pat, "  afd [asd] [12 ] [a34]  [ -43 ]tt [+12]")))                                                                                                        
#[12, -43, 12]

推荐阅读