2016-09-15 60 views
1

我写这个正则表达式:Python的正则表达式搜索或匹配不工作

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作为输出。

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

+0

您需要使用点的所有标志修改'^ *节?:'行内,或者作为一个编译选项(S?)。问题在于冒号位于不同的行,并且默认选项是点'.'与换行符不匹配。我会把所有的修饰符内联:'(?ism)^ SECTION。* ?:' – sln

回答

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]: