# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"System Message: (?<agent>\w+) is ready to chat.*?[\r\n]+[\d\/]+\s+[\d:]+\s+\w+\s+[\r\n]+(?P=agent)[\r\n]+(?<agentFirstResponse>.*?)[\r\n]+[\d\/]+\s+[\d:]+\s+\w+"
test_str = ("1/1/2019 2:42:55 AM \n"
"Aju \n"
"Hi Team\n\n"
"1/1/2019 2:42:56 AM \n"
"System \n"
"The data has been added: \n"
"- Customer Info\n\n"
"1/1/2019 2:42:59 AM \n"
"Rohi\n"
"System Message: Rohi is ready to chat. \n\n"
"1/1/2019 2:43:09 AM \n"
"Aju \n"
"Wish you a very happy ne year \n\n"
"1/1/2019 2:43:12 AM \n"
"Aju \n"
"new* \n\n"
"1/1/2019 2:43:25 AM \n"
"Aju \n"
"I need to KNOW ABOUT A CAR\n\n"
"1/1/2019 2:43:32 AM \n"
"Aju \n"
"please help me \n\n"
"1/1/2019 2:45:07 AM \n"
"Aju \n"
"Anyone there ? \n\n"
"1/1/2019 2:47:13 AM \n"
"Aju \n"
"?? \n\n"
"1/1/2019 2:49:23 AM \n"
"Aju \n"
"?? Hi Rohi You there? \n\n"
"1/1/2019 2:51:16 AM \n"
"Rohi\n"
"Hello Aju my name is Rohi. How can I help you today? \n\n"
"1/1/2019 2:51:27 AM\n\n"
"Chat goes on....")
matches = re.finditer(regex, test_str, re.MULTILINE | re.DOTALL)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html