1

Using python, I need to extract an ID and Date from this filename:

export-foobar-54321-2015_02_18_23_30_00.csv.gz

Where: ID = 54321 Date = 2015_02_18

So far, I can match the file name with this regular expression:

export-foobar-[0-9]{5}\-[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}.csv.gz

What I'd like as my final print out put would be:

ID = 54321 Date =02-18-2015

Being new to python, I tried the following, however, im not sure how to print what I need. I have this so far:

>>> import re
>>> filename='export-generic-33605-2015_02_18_23_30_00.csv.gz'
>>> matches=re.search("export-foobar-[0-9]{5}\-[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}.csv.gz",filename)
>>> print(matches)
<_sre.SRE_Match object at 0x7f2ee3616718>

If I could please get some help in printing out what I need and then customizing the print to match the date MM-DD-YYYY correctly would be appreciated.

2 Answers 2

3

Use capturing groups and also replace foobar in your regex to generic or use [^-]+ instead of generic if you don't know the actual value.

>>> import re
>>> filename='export-generic-33605-2015_02_18_23_30_00.csv.gz'
>>> matches=re.search(r"export-generic-([0-9]{5})-([0-9]{4}_[0-9]{2}_[0-9]{2})_[0-9]{2}_[0-9]{2}_[0-9]{2}\.csv\.gz",filename).groups()
>>> Id, Date = matches
>>> Id
'33605'
>>> Date
'2015_02_18'
>>> date = re.sub(r'^([^_]+)_([^_]+)_([^_]+)$', r'\2-\3-\1', Date)
>>> date
'02-18-2015'
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the following to capture the digits of interest and rearrange the date. generic in your regexp was changed to \w+ to capture any text string.

filename = 'export-foobar-54321-2015_02_18_23_30_00.csv.gz'

matches=re.search(r"export-\w+-([0-9]{5})-([0-9]{4})_([0-9]{2})_([0-9]{2})_[0-9]{2}_[0-9]{2}_[0-9]{2}\.csv\.gz",filename).groups()
Id, Year, Month, Day = matches
Date = '-'.join([Month, Day, Year])

print(Id) # 54321
print(Date) # 02-18-2015

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.