python - 无法阻止我的脚本抓取不必要的行
问题描述
我在 python 中编写了一个脚本来从文本容器中获取某些信息。我使用re
模块来完成这项工作。但是,它给了我不必要的输出以及所需的输出。
如何修改我的表情以坚持我想要抓住的线条?
这是我的尝试:
import re
content = """
A Gross exaggeration,
-- Gross 5 90,630,08,
Gross 4 13,360,023,
Gross 2 70,940,02,
Luke gross is an actor
"""
for item in re.finditer(r'Gross(?:[\d\s,]*)',content):
print(item.group().strip())
我得到的输出:
Gross
Gross 5 90,630,08,
Gross 4 13,360,023,
Gross 2 70,940,02,
我希望拥有的输出:
Gross 4 13,360,023
Gross 2 70,940,02
解决方案
我将正则表达式字符串更改为r'(?:^\s*?)Gross[\d\s,]*?(?=,$)'
并添加了多行标志(此处为在线正则表达式):
import re
content = """
A Gross exaggeration,
-- Gross 5 90,630,08,
Gross 4 13,360,023,
Gross 2 70,940,02,
Luke gross is an actor
"""
for item in re.finditer(r'(?:^\s*?)Gross[\d\s,]*?(?=,$)',content, flags=re.M):
print(item.group().strip())
输出是:
Gross 4 13,360,023
Gross 2 70,940,02
推荐阅读
- typeorm - TypeORM:如何计算关系并将它们转换为布尔值
- roku - 是否可以在任务节点响应完成之前显示加载指示器?
- python - 组合两个查询集,具有不同值的公共字段
- javascript - 在 React 组件中定义函数有什么好处吗?
- android - 如何使用 adb shell 命令禁用 Android 11(API 30)中的位置
- regex - 使用 Matcher 提取子字符串:java.lang.IllegalStateException: No match found
- html - 我的谷歌图片搜索输入字段不起作用
- google-compute-engine - 初始化扳手客户端缺少哪个权限?
- spring-boot - 使用 springboot 从可流动的运行时服务中检索变量
- c# - .NET Core "RuntimeInformation.OSDescription" 属性(以及一般的 .Net Core Multi-Platform 支持实现)