Domanda

So I need a bit of advice on how to catch a file name and it's structure. Let me explain just a little bit. A piece of software will upload an mp3 file into a directory. That mp3 file will always hold a format that closely resembles this:

Station-[_A]_Warren_2014-01-2614_40_01_377000.mp3

Anything to the right, and including 2014, will generally always stay the same. Of course the Year-Month-DayHour-Minute-Second-Milliseconds.mp3 will vary as time progresses. But what I need to be able to do is catch whatever is in front of the 2014 (Year) and the best way possible to do so.

I could explode the "_" but that really won't work as I need, because if I look to see if $array[x] = 2014, that placement of 2014 could vary. One time it could be in placement 2, or the next time it could be in placement 8, depending on how the user has structured their file name, as the software will re-write special characters to underscores.

So I need to figure out the best way to catch whatever is in front of the 2014. Any thoughts?

È stato utile?

Soluzione

The strictest way to do it is with this regex:

^(.*?)\d{4}-\d{2}-\d{4}_\d{2}_\d{2}_\d{6}\.mp3

The result will be in the first capturing group.

The regex only assumes the format of the date is fixed. It will work correctly even if the name contains some numbers.


Alternatively, if you can assume that the format of the date time is consistent, you can just do a substring that takes from (0, length - 29).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top