views:

768

answers:

2

I need to parse the first 10 chars of a file name to see if they are all digits. The obvious way to do this is fileName =~ m/^\d{10}/ but I'm not seeing anything regExy in the applescript reference, so, I'm curious what other options I have to do this validation.

+1  A: 

I'm sure there is an Applescript Addition or a shell script that can be called to bring regex into the fold, but I avoid dependencies for the simple stuff. I use this style pattern all the time...

set filename to "1234567890abcdefghijkl"

return isPrefixGood(filename)

on isPrefixGood(filename) --returns boolean
    set legalCharacters to {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}

    set thePrefix to (characters 1 thru 10) of filename as text

    set badPrefix to false

    repeat with thisChr from 1 to (get count of characters in thePrefix)
     set theChr to character thisChr of thePrefix
     if theChr is not in legalCharacters then
      set badPrefix to true
     end if
    end repeat

    if badPrefix is true then
     return "bad prefix"
    end if

    return "good prefix"
end isPrefixGood
Philip Regan
thanks! that's very useful (albeit not as elegant as m/^\d{10}/) :)
Dr.Dredel
+4  A: 

Don't despair, since OSX you can also access sed and grep through "do shell script". So:

set thecommandstring to "echo \"" & filename & "\"|sed \"s/[0-9]\\{10\\}/*good*(&)/\"" as string
set sedResult to do shell script thecommandstring
set isgood to sedResult starts with "*good*"

My sed skills aren't too crash hot, so there might be a more elegant way than appending *good* to any name that matches [0-9]{10} and then looking for *good* at the start of the result. But basically, if filename is "1234567890dfoo.mov" this will run the command:

echo "1234567890foo.mov"|sed "s/[0-9]\{10\}/*good*(&)/"

Note the escaped quotes \" and escaped backslash \\ in the applescript. If you're escaping things in the shell you have to escape the escapes. So to run a shell script that has a backslash in it you have to escape it for the shell like \\ and then escape each backslash in applescript like \\\\. This can get pretty hard to read.

So anything you can do on the command line you can do by calling it from applescript (woohoo!). Any results on stdout get returned to the script as the result.

stib