Извлечь строку после двоеточия или круглой скобки с регулярным выражением в python - PullRequest
0 голосов
/ 10 июля 2020

ввод:

Subject: Representation of Territories? (Was: Re: The $11,250,000,000,000 lunch)

вывод:

Representation of Territories

ввод:

Subject: Re: Top Ten Responses to Ed's Top Ten Lists

вывод:

Top Ten Responses to Ed's Top Ten Lists

1 Ответ

0 голосов
/ 10 июля 2020

Вы можете сделать это с помощью дополнительной группы захвата:

import re

text_1 = "Subject: Representation of Territories? (Was: Re: The $11,250,000,000,000 lunch)"
text_2 = "Subject: Re: Top Ten Responses to Ed's Top Ten Lists"

regex = re.compile(r"Subject:\s"
                   r"(?:\w{2}:\s)?"  # Optional capture group
                   r"((\w+[']?\w+?\s?)+\w)"
                   r"\??",
                   re.I
                   )

res_1 = re.search(regex, text_1).group(1)
res_2 = re.search(regex, text_2).group(1)

print(res_1)
print(res_2)

Возврат:

Representation of Territories
Top Ten Responses to Ed's Top Ten Lists

Добавление, как указано в комментариях:

text_3 = "Subject: Re: F<O>CUS/HEALTH: ONE PAYER SYSTEM B.S."
regex_3 = re.compile(r"(.*:\s)+(.*)")
res_3 = re.search(regex_3, text_3).group(2)
print(res_3)

Возврат:

ONE PAYER SYSTEM B.S.
...