I'm posting this variant in the hopes that it will be a little more educational. Otherwise doesn't add anything over Kuba's version.
Generally, parsing can be done using StringCases
. You'll need to build up a string expression that describes the pattern of the file name, much the same way you'd write "%d_%s_Polarizer%dDeg-Temp%dK.dpt"
when working with scanf
. Except here %d
is called a NumberString
, %s
is __
, etc. (Note: scanf
wouldn't actually work here because it doesn't know that it has to stop reading the %s
as soon as it encounters _
. scanf
doesn't do pattern matching.)
So let's build up the pattern:
StringCases["20140605_SampleName-C-vert_Polarizer90Deg-Temp100K.dpt",
date : NumberString ~~
"_" ~~ name__ ~~
"_Polarizer" ~~ angle : NumberString ~~
"Deg-Temp" ~~ temp : NumberString ~~
"K.dpt" :> {DateList[date], name, FromDigits[angle], FromDigits[temp]}
]
(* ==> {{{2014, 6, 5, 0, 0, 0.}, "SampleName-C-vert", 90, 100}} *)
Since it's just a string of atomic constructs, it should be fairly self explanatory.
This basic pattern doesn't account for file names which do not have the -Temp
part. Fortunately the fix is easy: just make that part of the pattern optional, i.e. allow it to be [Repeated
](http://reference.wolfram.com/mathematica/ref/Repeated .html)zero or 1 times.
StringCases["20140605_SampleName-C-vert_Polarizer90Deg.dpt",
date : NumberString ~~
"_" ~~ name__ ~~
"_Polarizer" ~~
angle : NumberString ~~
"Deg" ~~
Repeated["-Temp" ~~ temp : NumberString ~~ "K", {0, 1}] ~~
".dpt" :> {DateList[date], name, angle, temp}]
(* ==> {{{2014, 6, 5, 0, 0, 0.}, "SampleName-C-vert", "90", ""}} *)
If you are already familiar with regular expressions, or if you do not like the wordiness of Mathematica's pattern language, you can use RegularExpression
to implement the same thing:
StringCases["20140605_SampleName-C-vert_Polarizer90Deg-Temp100K.dpt",
RegularExpression["([0-9]*)_(.*?)_Polarizer([0-9]*)Deg(-Temp([0-9]*)K)?\\.dpt"] :>
{"$1", "$2", "$3", "$5"}
]