删除 Applescript 中的部分字符串

Removing part of string in Applescript

所以我有一个字符串,但我只想要它在某个部分之后。我知道您最好在 shell 中执行此操作,所以我尝试了,但我有限的 shell 知识并没有让我走得太远。 This post 尝试做类似的事情,但不完全是我需要的。

set theString to "hello/world"
do shell script "echo " & theString & "???"
return theString --the output should be hello

不需要 shell 脚本。获取斜线在字符串中的位置和return从头到位置-1

的子串
set theString to "hello/world"
set slashIndex to offset of "/" in theString
return text 1 thru (slashIndex - 1) of theString

这也有效。

set theString to "hello/world"
set firstWord to 1st word of theString

return firstWord

如果 theString 中有任何其他字符,包括“/”,下面应该处理它。

set theString to "hello/world"

set firstWord to 1st word of (do shell script "echo " & ¬
    quoted form of theString & " | sed -E 's@[^[:alpha:]]{1,}@ @'")

return firstWord

您还可以使用 AppleScript 的 文本项分隔符:

set theString to "hello/world"

set {TID, AppleScript's text item delimiters} to ¬
    {AppleScript's text item delimiters, "/"}
set theString to first text item of theString
set AppleScript's text item delimiters to TID

do shell script "echo " & theString's quoted form & "???"

Returns:

hello???

然而,return theString 在使用 AppleScript 的 文本项定界符 处理后将只是 return hello 在这个用例中。


请注意 theString's quoted form 中的 's quoted formdo shell script 命令中的 变量 的使用],因为您应该始终 quote 传递给 shell 的内容。您也可以使用这种形式:quoted form of theString

如您所见,其他答案之一中提供的 offset of 方法更为直接,但我已将其添加为答案,因此您知道您的另一个答案是什么选项是。