2016-09-15 90 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]: