首页 > 解决方案 > 无法阻止我的脚本抓取不必要的行

问题描述

我在 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

标签: pythonregexpython-3.x

解决方案


我将正则表达式字符串更改为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

推荐阅读