python,提取最外面的括号

时间:2015-02-12 09:38:24

标签: python

我有以下代码尝试从模板文件中提取msgids:

>>> import re
>>> string1 = '''p=t("Because of the high quality surface finish, our garments perform particularly well with digital direct-to-garment (DTG) printing.")'''
>>> string2 = '''p=t("The carbon footprint (CO2e) is the total carbon dioxide, methane, nitrous oxide, and other greenhouse gases emitted during the cultivation and harvesting of cotton, fibre processing, textile production, packaging, transportation and warehousing. In January 2008, Clothing Co.  became the first company in the world to calculate the carbon footprint and place the Carbon Reduction Label on textile products.")'''
>>> string3 = '''USER_REGISTERED_AND_ACTIVE: "The email address entered is already registered. <br>Please <a href='/login'>(Login)</a>"'''
>>> string4 = '''p!=t("We received your application to become an additional user for an account on <strong>__date__</strong>.")'''
>>> string5 = '''p=#{t("We received your order on")}'''
>>> gettext_messages = re.compile(r"""\:(.*)""", re.MULTILINE).findall
>>> for string in [string1, string2, string3, string4, string5]:
...     msgids = gettext_messages(string)
...     print msgids
... 
[]
[]
[' "The email address entered is already registered. <br>Please <a href=\'/login\'>(Login)</a>"']
[]
[]
>>> gettext_re = re.compile(r"""[=|#]t\((.*?)\)""").findall
>>> for string in [string1, string2, string3, string4, string5]:
...     msgids = gettext_re(string)
...     print msgids
... 
['"Because of the high quality surface finish, our garments perform particularly well with digital direct-to-garment (DTG']
['"The carbon footprint (CO2e']
[]
['"We received your application to become an additional user for an account on <strong>__date__</strong>."']
[]

这很有用,因为如果一个字符串包含另一组( ),那么它就会失败。

任何建议非常感谢

1 个答案:

答案 0 :(得分:1)

好吧,它应该像

一样
gettext_re = re.compile(r"""[=|#|{]t\((.*?)\"\)""").findall