首页 > 解决方案 > AppleScript中是否有类似array.split的函数

问题描述

因此,在 Javascript 中,您可以按照以下方式编写一些内容:

let array = "This.should.be.an.array";
array = array.split(".");
console.log(array)

/* This,should,be,an,array */

现在我知道在 Applescript 中有:

set theText to "This should be a list"
set theList to every word of theText
return theList

{"This", "should", "be", "a", "list"}

并且:

set theText to "This
should
be
a
list"
set theList to every paragraph of theText
return theList

{"This", "should", "be", "a", "list"}

并且:

set theText to "Thisshouldbealist"
set theList to every character of theText
return theList


{"T", "h", "i", "s", "s", "h", "o", "u", "l", "d", "b", "e", "a", "l", "i", "s", "t"}

但我不知道如何拆分单词之间有句点的列表。

标签: javascriptarraysapplescript

解决方案


不久前我正在寻找同样的东西,答案并不那么简单。你必须使用Applescript's text item delimiters. 如果您想按句点拆分字符串,您将拥有如下内容:

set array to "This.should.be.an.array"
set AppleScript's text item delimiters to "."
set array to every text item of array
set AppleScript's text item delimiters to ""

或者写成一个函数,它看起来像这样:

on split(theString, theSplitter)
    set AppleScript's text item delimiters to theSplitter
    set theString to every text item of theString
    set AppleScript's text item delimiters to ""
    return theString
end split

这是一种保留Erik 在 erikslab.com 上发布的旧分隔符的方法:

on theSplit(theString, theDelimiter)
    -- save delimiters to restore old settings
    set oldDelimiters to AppleScript's text item delimiters
    -- set delimiters to delimiter to be used
    set AppleScript's text item delimiters to theDelimiter
    -- create the array
    set theArray to every text item of theString
    -- restore the old setting
    set AppleScript's text item delimiters to oldDelimiters
    -- return the result
    return theArray
end theSplit

推荐阅读