Extraction information that comes after a specific value using regular expressions

Viewed 36

I have a file I want to extract some data from using regex that looks like bellow :

RID:  RSS-120                                         TEST                        
FOR:      8999999 SSSE                      INT SER                   PROC DATE:   19SEP21  
TO:          8999999 SSSE INT VAL                               RT DATE: 19SEP21 
AQT TEST
T PURC                                              80            8,243,518RR             19,58.85 
MSS TRANS
T PURC                                              102           12,1234,70RR                                 12,83.64

RID:  RSS-130                                         TEST                        
FOR:      8999999 SSSE                      INT SER                   PROC DATE:   19SEP21  
TO:          8999999 SSSE INT VAL                               RT DATE: 19SEP21 
AQT TEST
T PURC                                              80            8,243,518RR             19,58.85 
MSS TRANS
T PURC                                              102           12,1234,70RR                                 12,83.64

RID:  RSS-140                                         TEST                        
FOR:      8999999 SSSE                      INT SER                   PROC DATE:   19SEP21  
TO:          8999999 SSSE INT VAL                               RT DATE: 19SEP21 
AQT TEST
T PURC                                              80            8,243,518RR             19,58.85 
MSS TRANS
T PURC                                              102           12,1234,70RR                                 12,83.64

Here are the regex I came up with :

regex_1 = "PROC DATE:\s+(\w+).*?" # to get 19SEP21  
regex_2 = "T PURC\s*(\d*)\s*([-.,0-9]+)" # To get the two values after T PRUC

The regex returns multiple matches obviously, but I want to specify only the line that comes after RID: RSS-130 and AQT TEST

Desired output :

[(19SEP21,80,8,243,518RR)]
1 Answers

I think the following two regexes will do the job:

regex_1 = "[RID:\s+RSS\-130].+\n.+PROC DATE:\s+(\w+).*?"
regex_2 = "AQT TEST\nT PURC\s*(\d*)\s*([-.,0-9]+RR)"

Here is what I mean:

>>> import re
>>> 
>>> set(re.findall(regex_1, text) #text is the file content
{'19SEP21'}
>>>
>>> set(re.findall(regex_2, text)
{('80', '8,243,518RR')}
Related