简体   繁体   English

正则表达式:匹配模式失败

[英]Regex: matching pattern fails

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.我正在尝试将模式与 python 中的 re 匹配,但无论我如何尝试,我似乎都无法匹配。

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我正在努力争取Q2 2018

But I keep getting empty strings.但我不断收到空字符串。

RegExp: r'(Q\\d\\s\\d+\\s)'正则表达式: r'(Q\\d\\s\\d+\\s)'

Explanation:解释:

  1. r prefix for raw string原始字符串的r前缀
  2. Q to match the Q of quarter Q匹配季度的Q
  3. \\d to match the quarter number afterward \\d之后匹配季度号
  4. \\s to match space \\s匹配空格
  5. \\d+ to match multiple numbers which are the year \\d+匹配多个年份的数字
  6. \\s to match space \\s匹配空格

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM