AppleScript中的字符串操作

时间:2009-07-15 07:27:43

标签: string applescript data-manipulation

我在AppleScript中遇到了如下操作字符串的挑战:

  • 基本字符串是电子邮件收件人显示名称,例如:First Last (first.last@hotmail.com)
  • 我想“修剪”显示名称以删除括号中的实际电子邮件地址
  • 所需的结果应为First Last - 因此需要移除第一个支架前面的空间。

在AppleScript中执行此操作的最佳和最有效的方法是什么?

3 个答案:

答案 0 :(得分:3)

set theSample to "First Last (first.last@hotmail.com)"

return trimEmailAddress(theSample)
-->Result: "First Last"

on trimEmailAddress(sourceAddress)
    set AppleScript's text item delimiters to {" ("}
    set addressParts to (every text item in sourceAddress) as list
    set AppleScript's text item delimiters to ""
    set nameOnly to item 1 of addressParts

    return nameOnly
end trimEmailAddress

答案 1 :(得分:3)

我也会使用补偿。 text 1 thru 2 of "xyz"相当于items 1 thru 2 of "xyz" as string

set x to "First Last (first.last@hotmail.com)"
set pos to offset of " (" in x
{text 1 thru (pos - 1) of x, text (pos + 2) thru -2 of x}

据我所知,you don't have to restore text item delimiters

set x to "First Last (first.last@hotmail.com)"
set text item delimiters to {" (", ")"}
set {fullname, email} to text items 1 thru 2 of x

如果其他人一般都在搜索字符串操作,下面是替换和拆分文本以及加入列表的方法:

on replace(input, x, y)
    set text item delimiters to x
    set ti to text items of input
    set text item delimiters to y
    ti as text
end replace

on split(input, x)
    if input does not contain x then return {input}
    set text item delimiters to x
    text items of input
end split

on join(input, x)
    set text item delimiters to x
    input as text
end join

字符串比较默认忽略大小写:

"A" is "a" -- true
"ab" starts with "A" -- true
considering case
    "A" is "a" -- false
    "ab" starts with "A" -- false
end considering

撤消文字:

reverse of items of "esrever" as text

您可以使用do shell脚本来更改文本的大小写:

do shell script "printf %s " & quoted form of "aä" & " | LC_CTYPE=UTF-8 tr [:lower:] [:upper:]" without altering line endings

echo默认在OS X的/ bin / sh中解释转义序列。您也可以使用shopt -u xpg_echo; echo -n代替printf %sLC_CTYPE=UTF-8使字符类包含一些非ASCII字符。如果省略without altering line endings,则换行替换为回车符,并删除输出末尾的换行符。

paragraphs of将字符串拆分为\ n,\ r和\ r \ n。它不会剥离分隔符。

paragraphs of ("a" & linefeed & "b" & return & "c" & linefeed)
-- {"a", "b", "c", ""}

剪贴板的纯文本版本使用CR行结尾。这会将行结尾转换为LF:

set text item delimiters to linefeed
(paragraphs of (get the clipboard as text)) as text
自从10.5以来,

Unicode text已与textstring等效:

  

Unicode和非Unicode文本之间不再有区别。只有一个文本类,名为“text”:即“foo”类返回文本。

答案 2 :(得分:1)

您可能想要使用更简单的解决方案:

set theSample to "First Last (first.last@hotmail.com)"

on trimEmailAddress(sourceAddress)
    set cutPosition to (offset of " (" in sourceAddress) - 1
    return text 1 thru cutPosition of sourceAddress
end trimEmailAddress

return trimEmailAddress(theSample)
-->  "First Last"