获取具有特定内容的列表项

时间:2014-06-07 13:49:29

标签: applescript

如何获取包含特定内容的列表项?

例如:

set listItems to {"abc","a bc","a(b)c","(bc"}
get every item which contains "a" of listItems

期望的结果:“abc”,“a bc”,“a(b)c”

get every item which contains "(" and ")" of listItems

期望的结果:“a(b)c”

我已经阅读了基本教程:http://www.macosxautomation.com/applescript/sbrt/sbrt-07.html所以我对任何类型的解决方法感兴趣。

2 个答案:

答案 0 :(得分:1)

我认为纯苹果中没有一个oneliner。你必须循环这些项目。像这样:

set listItems to {"abc", "a bc", "a(b)c", "(bc"}

my searchForPatterns(listItems, {"a"})
--result: {"abc", "a bc", "a(b)c"}

my searchForPatterns(listItems, {"(", ")"})
--result: {"a(b)c"}

on searchForPatterns(listItems, searchPatterns)
    set resultList to {}
    repeat with listItem in listItems
        set match to true

        repeat with searchPattern in searchPatterns
            if listItem does not contain searchPattern then ¬
                set match to false
        end repeat

        if match is true then ¬
            copy listItem as text to end of resultList
    end repeat
    return resultList
end searchForPatterns

答案 1 :(得分:1)

您可以简单地遍历列表并测试匹配项:

set listItems to {"abc", "a bc", "a(b)c", "(bc"}
set finalItems to {}
repeat with thisItem in listItems
    if (thisItem contains "(") and (thisItem contains ")") then set finalItems to finalItems & thisItem
end repeat
return finalItems