-1

Trying to find the latest version of a list of strings. For example,

"01022021_1"
"01032021_1"
"02032021_1"
"02032021_2"

The most recent is going to be the last one, but how can I use regex to take those strings and pick out the latest dated and versioned name?

So these are dates with a version number.

caasswa
  • 501
  • 3
  • 10

3 Answers3

8

Use max() with a key that extracts and reorders the parts of the string so the year is most significant.

max(yourList, key = lambda s: (s[4:8], s[:4], int(s[8:])))
#                              YYYY    MMDD   VERSION
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

If you can guarantee the format of your strings (that is (I think), DDMMYYYY_v, where v is version), then you could use max(), as has been suggested in the comments.

Blair Nangle
  • 1,221
  • 12
  • 18
0

if it's a list of strings, and the last element in the list is always the latest, the simplest would be the following:

stringlist = [
    "01022021_1",
    "01032021_1",
    "02032021_1",
    "02032021_2"]

latest = stringlist[-1]
print(latest)

# output:
# 02032021_2

List handling is extremely easy in python. Using a negative number means you start counting from the end of the list.

Edo Akse
  • 4,051
  • 2
  • 10
  • 21