(*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FILTERING LISTS
List Manipulation Routines
http://www.macosxautomation.com/applescript/sbrt/sbrt-07.html
Working with lists is one of the most common procedures performed in scripts.
However, the current version of AppleScript does not support
the use of every...whose clauses when targeting lists.
For example, the following statement will not work:
### DOES NOT WORK ###
set the name_list to {"Bob", "Sal", "Wanda", "Sue"}
set every item of the name_list where it is "Bob" to "Carl"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*)
use AppleScriptversion
"2.4"
-- Yosemite (10.10) or later
use scripting additions
set myList to {"@Test",
"other", "@end",
"else"}
--text of every item in myList that begins with "@" ### FAILS
set
startsList to my filterList(myList,
"@", "starts with")
set
endsList to my filterList(myList,
"end", "ends with")
set containsList to my
filterList(myList,
"the",
"contains")
on filterList(pList,
pMatchStr, pMatchType)
### Since lists don't support "whose" or "where" clauses,
# have to roll my own.
local foundItems,
oItem
set
foundItems to {}
repeat with
oItem in pList
if (pMatchType =
"starts with") then
if (oItem starts with
pMatchStr) then
set end of
foundItems to text of
oItem
end if
else if (pMatchType =
"ends with") then
if (oItem ends with
pMatchStr) then
set end of
foundItems to text of
oItem
end if
else if (pMatchType =
"contains") then
if (oItem contains
pMatchStr) then
set end of
foundItems to text of
oItem
end if
end if
end repeat
return foundItems
end filterList