Search code examples
pythonstringtextsubquerymatch

How to get the sentence / string with the matched substring


If the following content is given in a text file,

Text1.txt

Registered : [10-01-21] Left : [12-02-21]

Approved : [03-03-21] Name : Ann

Ann submitted documents. Ann checked [12-04-21]


I need to get the output as :

Registered : [10-01-21]        
Left : [12-02-21]           
Approved : [03-03-21]       
checked [12-04-21]          

As the substring, we can give a regex to validate the date format.
import re
f1= open("Text1.txt")
string=f1.read()

found_p1=re.findall(r"(.*)\[[0-9]{2}[-][0-9][2][-][0-9]{2}\](.*)" ,string)
k=[ ]
for i in found_p1:
    i=re.sub(r"|',|'(|)", "", str(i))

Solution

  • try this:

    import re
    
    f = open("Text1.txt")
    string = f.read()
    
    pattern = re.compile("(\w+\s\[\d{2}[-]\d{2}[-]\d{2}\]|\w+\s[:][\s]\[\d{2}[-]\d{2}[-]\d{2}\])")
    m = pattern.findall(string)
    for i in m:
        print(i)