我试图用Python编写一个正则表达式,从以下字符串中提取两个数字:
这是为了对正在使用的工具进行概述。因此,我只需要字符串中的数字。在字符串中,只有"tool“一词会根据工具的数量而变化。我尝试过几种解决方案来编译字符串,但很难最终确定解决方案。
[...]
regexToolUsage = re.compile(r"\((\S)(\d+)(\S)(\d+)(\d)\)"))
[...]
if ToolUsage != None:
ToolsInTotal = ToolUsage.group(2).strip()
ToolsInUse = ToolUsage.group(4).strip()我期望输出64和8,但收到以下错误: UnboundLocalError:赋值前引用的局部变量'ToolsInTotal‘。
我还尝试了以下表达方式:
re.compile(r"(Total of)(.+)( issued; Total of)(.+)(in use)\)")
这提取了"64工具“和"8工具”,但我只需要一个数字。我不能添加“工具”一词,因为如果它只是“1个工具”,就不会得到承认。有人能提供帮助吗?
发布于 2019-10-02 08:58:41
以下是从字符串中获取所有整数的方法:
import re
s = "Total of 64 tools issued; Total of 8 tools in use"
r = re.findall("\d+", s) # 'r' is now ['64', '8']发布于 2019-10-02 12:45:54
import re
text = """(Total of 64 tools issued; Total of 8 tools in use)
(Total of 49 tools issued; Total of 13 tools in use)
(Total of 3 tools issued; Total of 1 tool in use)"""
l = [
(m.group(1), m.group(2))
for m in re.finditer(r'\(Total of (\d+) tools? issued; Total of (\d+) tools? in use\)', text)
]
print(l)指纹:
[('64', '8'), ('49', '13'), ('3', '1')]https://stackoverflow.com/questions/58198275
复制相似问题