Regex: matching pattern fails

Viewed 33

I'm trying to match a pattern with re in python, but I can't seem to get a match no matter how I try.

This is my matching pattern:

def get_report_date(report):
    report_data = {}
    with open(report, 'r') as f:
        report_date = re.findall(f'([Q\d \d\d\d\d\s])', f.read())[0]
        pprint(report_date)
        report_data.update({f"{report_date.replace(' ', '_')}": report})
        return report_data

and a piece of the file I'm trying to match:

(In millions, except number of shares which are reflected in thousands and per share amounts) 

See accompanying Notes to Condensed Consolidated Financial Statements. 

Apple Inc. | Q2 2018 Form 10-Q | 1 Apple Inc. CONDENSED CONSOLIDATED STATEMENTS OF COMPREHENSIVE INCOME (Unaudited)

I'm trying to scrape the Q2 2018

But I keep getting empty strings.

1 Answers

RegExp: r'(Q\d\s\d+\s)'

Explanation:

  1. r prefix for raw string
  2. Q to match the Q of quarter
  3. \d to match the quarter number afterward
  4. \s to match space
  5. \d+ to match multiple numbers which are the year
  6. \s to match space

Example:

import re

text = """(In millions, except number of shares which are reflected in thousands and per share amounts)

See accompanying Notes to Condensed Consolidated Financial Statements.

Apple Inc. | Q2 2018 Form 10-Q | 1 Apple Inc. CONDENSED CONSOLIDATED STATEMENTS OF COMPREHENSIVE INCOME (Unaudited)"""


x = re.findall(r'(Q\d\s\d+\s)', text)[0]

# Q2 2018 
print(x)

Code Fix:

def get_report_date(report):
    report_data = {}
    with open(report, 'r') as f:
        report_date = re.findall(r'(Q\d\s\d+\s)', f.read())[0]
        pprint(report_date)
        report_data.update({f"{report_date.replace(' ', '_')}": report})
        return report_data
Related