python - 编写一个函数以使用正则表达式从字符串中提取整数
问题描述
尝试编写函数 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%[????????????????????????????????????????????????????????????????]
解决方案
这应该有效:
import re
pat=r"(?:\[(\s*?[-+]?\d+\s*?)\])"
list(map(eval, re.findall(pat, " afd [asd] [12 ] [a34] [ -43 ]tt [+12]")))
#[12, -43, 12]
推荐阅读
- javascript - 如何在扩展的帮助下获取会话期间传输的数据量?
- sql - 是否可以通过在 PostgreSQL 中使用窗口函数来找出一行中的项目数?
- python - 在运行时创建一个函数,该函数在 python 中具有特定数量的参数
- sql - UNNEST ARRAY 和 UNION ALL 到具有字符串值的其他表
- python - Python - 调整函数以接受数组而不是单个值
- arrays - C函数不修改传递的数组
- kafka-topic - 如何计算每秒输出的 kafka 字节数?
- css - Vuetify:查找 v-menu 内容的宽度
- html - 如何在 css 中进行嵌套并将其与 html 链接?
- html - 为什么内联块元素中的两个输入是一个输入的两倍?