Python正则表达式搜索或匹配不起作用

时间:2016-09-15 23:19:26

标签: python regex

我写了这个正则表达式:

 re.search(r'^SECTION.*?:', text, re.I | re.M)
 re.match(r'^SECTION.*?:', text, re.I | re.M)

在此字符串上运行:

text = 'SECTION 5.01. Financial Statements and Other Information. The Parent\nwill furnish to the Administrative Agent:\n          (a) within 95 days after the end of each fiscal year of the Parent,\n     its audited consolidated balance sheet and related statements of income,\n     cash flows and stockholders\' equity as of the end of and for such year,\n     setting forth in each case in comparative form the figures for the previous\n     fiscal year, all reported on by Arthur Andersen LLP or other independent\n     public accountants of recognized national standing (without a "going\n     concern" or like qualification or exception and without any qualification\n     or exception as to the scope of such audit) to the effect that such\n     consolidated financial statements present fairly in all material respects\n     the financial condition and results of operations of the Parent and its\n     consolidated Subsidiaries on a consolidated basis in accordance with GAAP\n     consistently applied;\n          (b) within 50 days after the end of each of the first three fiscal\n     quarters of each fiscal year of the Parent, its consolidated balance sheet\n     and related statements of income, cash flows and stockholders\' equity as of\n     the end of and for such fiscal quarter and the then elapsed portion of the\n     fiscal year, setting forth in each case in comparative form the figures for\n     the corresponding period or periods of (or, in the case of the balance\n     sheet, as of the end of) the previous fiscal year, all certified by one of\n     its Financial Officers as presenting fairly in all material respects the\n     financial condition and results of operations of the Parent and its\n     consolidated Subsidiaries on a consolidated basis in accordance with GAAP\n     consistently applied, subject to normal year-end audit adjustments and the\n     absence of footnotes;\n          '

我期待以下输出:

SECTION 5.01. Financial Statements and Other Information. The Parent\nwill furnish to the Administrative Agent:

但我得到None作为输出。

请有人告诉我这里我做错了什么?

1 个答案:

答案 0 :(得分:1)

.*将匹配所有文字,由于您的文字未以:结尾,因此会返回None。您可以使用否定的字符类来获得预期的结果:

In [32]: m = re.search(r'^SECTION[^:]*?:', text, re.I | re.M)

In [33]: m.group(0)
Out[33]: 'SECTION 5.01. Financial Statements and Other Information. The Parent\nwill furnish to the Administrative Agent:'

In [34]: