我在 AppleScript 中遇到了如下操作字符串的挑战:
- 基本字符串是电子邮件收件人显示名称,例如:
First Last (first.last@hotmail.com)
- 我想“修剪”显示名称以删除括号中的实际电子邮件地址
- 期望的结果应该是
First Last
- 所以需要删除第一个括号前面的空间。
在 AppleScript 中执行此操作的最佳和最有效的方法是什么?
我在 AppleScript 中遇到了如下操作字符串的挑战:
First Last (first.last@hotmail.com)
First Last
- 所以需要删除第一个括号前面的空间。在 AppleScript 中执行此操作的最佳和最有效的方法是什么?
我也会使用偏移量。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}
据我所知,您不必恢复 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 script 更改文本的大小写:
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 %s
. LC_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
Unicode text
从10.5text
开始等效于:string
Unicode 和非 Unicode 文本之间不再有区别。只有一个文本类,名为“text”:即“foo”类返回文本。
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
您可能想要使用这样的更简单的解决方案:
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"