Maurdekye
Maurdekye

Reputation: 3697

Use regex to isolate information in filename

I have various files that are formatted like so;

file_name_twenty_135032952.txt

where file_name_twenty is a description of the contents, and 13503295 is the id. I want two different regexes; one to get the description out of the filename, and one to get the id.

Here are some other rules that the filenames follow:

I've been toiling for a while and can't seem to figure out a regex to solve this. I'm using python, so any limitations thereof with its regex engine follow.

Upvotes: 1

Views: 78

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180550

rsplit once on an underscore and to remove the extension from id.

s = "file_name_twenty_13503295.txt"

name, id = s.rsplit(".",1)[0].rsplit("_", 1)

print(name, id)

file_name_twenty 13503295

Upvotes: 4

Related Questions