Checking if the year is in a string (4 consecutive digits)

How can I find if the lines in the list contain the year (e.g. 1999 ). I think I would check four consecutive digits, such as: [1-2][0-9][0-9][0-9]

How to check it on a part of the list? Here is what I have already tried

 for piece in reflist: if "\d{4}" in piece: # Do something for piece in reflist: if re.match('\d{4}', piece): print piece + '\n' 
+4
source share
1 answer

You want to use re.search() to check for compliance anywhere in the input string.

To combine the (recent) years a little more precisely, you could use:

 re.search(r'[12]\d{3}', piece) 

which will match everyone from 1000 to 2999.

+9
source

All Articles