How can I match text that falls within specific parameters in Python?

Question:

I have a text file containing my TikTok video browsing data

It looks something like this:

Date: 2022-07-26 00:30:36
Video Link: https://www.tiktokv.com/share/video/7124308827599588614/

Date: 2022-07-26 00:30:31
Video Link: https://www.tiktokv.com/share/video/7124339950736166187/

Date: 2022-07-26 00:29:52
Video Link: https://www.tiktokv.com/share/video/7123899535344028933/

I want to write the Video Link that fall between 2022-07-22 & 2022-07-24 and write them to a new text file.

I know how to write data to text files; however, I do not know how I can only match those video links that fall within the dates I have specified.

How can I accomplish this?

Asked By: Nova

||

Answers:

One approach would be to read the entire text file into a string, and then use re.findall to find all date/link pairs. Then, filter that list using a comprehension such that only dates within in your range are retained.

inp = """Date: 2022-07-22 00:30:36
Video Link: https://www.tiktokv.com/share/video/7124308827599588614/

Date: 2022-07-24 00:30:31
Video Link: https://www.tiktokv.com/share/video/7124339950736166187/

Date: 2022-07-26 00:29:52
Video Link: https://www.tiktokv.com/share/video/7123899535344028933/"""

matches = re.findall(r'Date: (d{4}-d{2}-d{2}).*?bVideo Link: (https?://.*?/)n', inp, flags=re.S)
keep = [x[1] for x in matches if x[0] in ['2022-07-22', '2022-07-23', '2022-07-24']]
print(keep)

# ['https://www.tiktokv.com/share/video/7124308827599588614/',
   'https://www.tiktokv.com/share/video/7124339950736166187/']
Answered By: Tim Biegeleisen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.