python,提取最外层的括号

2024-10-01 00:14:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

>>> 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>."']
[]

这在一定程度上是有效的,因为如果一个字符串包含另一组( ),那么它就失败了。你知道吗

有什么建议吗


Tags: andofthetoreanforstring