仅从 AppleScript 中的字符串中提取字母字符

Extract only letter characters from a string in AppleScript

示例字符串如下:

“DOGE495.96”

我想使用 AppleScript 仅提取“DOGE”

我将如何完成这个?

我发现这种方法无需写出整个字母表就可以工作:

set theString to "DOGE495.96"
set newString to ""

repeat with i from 1 to count of characters in theString
    if id of character i of theString > 64 and id of character i of theString < 122 then set newString to newString & character i of theString
end repeat

return newString

输出:

"DOGE"

但是,这不适用于变音符号。对于那些,你必须做这样的事情:

set theString to "Ÿėś āńd Ñó"
set newString to ""

repeat with i from 1 to count of characters in theString
    ignoring diacriticals and case
        if "ABCDEFGHIJKLMNOPQRSTUVWXYZ" contains character i of theString then set newString to newString & character i of theString
    end ignoring
end repeat

return newString

输出:

"ŸėśāńdÑó"

不考虑更高级的变音符号,例如 ß,因为它们算作单独的字符。

这两种方法都不包含空格,对于下面的方法可以很容易地添加,对于上面的方法,if-statement 需要这样修改:

if (id of character i of theString > 64 and id of character i of theString < 122) or character i of theString = space then set newString to newString & character i of theString

如果您的源字符串始终仅包含字母、数字和“.”,那么一种非常快速且简单的解决方案是使用文本项分隔符。

set sourceString to "DOGE495.96"

set ATID to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."}
set tempString to text items of sourceString
set AppleScript's text item delimiters to ATID

set resultString to tempString as text

您可以使用 tr:

使用单个 shell 脚本只抓取字母
set sString to "DOGE495.96"

set lString to do shell script "echo " & sString & " | tr -cd '[[:alpha:]]'"

-c 让它使用最后一项的补码(或除最后一项之外的所有内容),在本例中为 'alpha' class 个字符。 -d 导致删除匹配的所有内容,在本例中,删除所有不是字母的内容。