I’m trying to get a script to determine whether a particular range of characters in a filename is a number. So far, no luck. Any ideas?
tell application "Finder"
set tokenFile to choose file
set firstCharCheck to characters 1 thru 13 of (name of tokenFile as text)
set numberCheck to false
if every item of firstCharCheck is integer then -- How do I check if it's a number?
display alert "13 are integers"
set numberCheck to true
end if
end tell
tell application "Finder"
set tokenFile to choose file
set firstCharCheck to characters 1 thru 13 of (name of tokenFile as text)
end tell
set numberCheck to true
repeat with char in firstCharCheck
try
set char to char as integer
on error
set numberCheck to false
exit repeat
end try
end repeat
return numberCheck
set tokenFile to choose file
try
text 1 thru 13 of name of (info for tokenFile) as integer
set numberCheck to true
on error
set numberCheck to false
end try
Notes:
The Finder is not needed at all for this check.
a file name is always (Unicode) text, so the coercion to text is useless
I like Stefan’s try loop as it will also catch a file that is less than 13 characters long. The previous examples would have errored in an ugly way.
As far as “1e2” successfully converting to an integer, is there any instance of such a string that is 13 characters long that would do the same thing? I don’t fully understand what 1e2 represents so I am not sure if it would be an issue for what this script is trying to accomplish.
“1e2” means “one times (ten to the two)” - scientific notation
how about this
set integer_list to {}
set tokenFile to choose file
set test_these to characters of name of (info for tokenFile)
repeat with testme in test_these
if ((ASCII number testme) > 47) and ((ASCII number testme) < 58) then
set end of integer_list to 1
else
set end of integer_list to 0
end if
end repeat
return integer_list
I didn’t say it wasn’t. It may in fact “be sufficient” for the task at hand.
Edit: Alternatively:
choose file without invisibles
try
do shell script "/usr/bin/basename " & quoted form of POSIX path of result & " | /usr/bin/grep '^[0-9]\\{13\\}'"
set numberCheck to true
on error
set numberCheck to false
end try