merely_oolong
merely_oolong

Reputation: 57

Using Regex in Ruby to parse out a chunk of file names

I am trying to standardize file names in a directory that have some similarities, but are not always consistent. They are, however, standard enough.

Examples of file names (where the date is Month/Day/Year):

My current solution has been an effective, but ugly find and replace for any possible string combinations. x.gsub!(/^Weekly|sales|report|U S|U.S.|\s/,'')

However, I would assume that there would be a way to look at the file name string and grab the chunk that has all of the date information. This would be the chunk bounded by whitespace on the left and ends in at least 4 digits. Is there a straightforward way to accomplish this?

Upvotes: 0

Views: 103

Answers (1)

Chowlett
Chowlett

Reputation: 46667

Your requirement as stated would suggest the following:

date_portion = x.match(/\s(\S*\d{4,8})/)[1]

That's: match one whitespace char, then capture zero-or-more non-whitespace, followed by 4 to 8 digits; return the captured text.

Upvotes: 2

Related Questions