[英]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:解释:
r
prefix for raw string原始字符串的r
前缀Q
to match the Q
of quarter Q
匹配季度的Q
\\d
to match the quarter number afterward \\d
之后匹配季度号\\s
to match space \\s
匹配空格\\d+
to match multiple numbers which are the year \\d+
匹配多个年份的数字\\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.