Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regular expression to filter out dates from a list

I have a list that looks like this:

['','2022-03-31', 'euss', 'projects','2021-03-31']

I want to write a regular expression such that I delete all other items from the list and only keep those that have a date format. For example, 2022-03-31 and 2021-03-31.

I tried this but it doesn’t seem to make a difference when I print my list out:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my_list = [re.sub(r"(\d+)/(\d+)/(\d+)",r"\3-\1-\2",i) for i in list(my_list) ]

>Solution :

You can first check if there regex matches the string:

result = []
rx = re.compile(r'(\d+)-(\d+)-(\d+)')
for i in my_list:
    if rx.search(i):                          # Check if the regex matches the string
        result.append(rx.sub(r"\3-\1-\2", i)) # Add modified string to resulting list

See the Python demo.
Output:

['31-2022-03', '31-2021-03']

You may write it as:

rx = re.compile(r'(\d+)-(\d+)-(\d+)')
my_list = [rx.sub(r"\3-\1-\2", i) for i in my_list if rx.search(i)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading