使用 Apple Script 更改字符串中单个单词的大小写

Changing the case of a single word in a string using Apple Script

所以我有 Apple 脚本:

-- Uses the satimage osax
-- Get it at http://www.satimage.fr/software/en/downloads/downloads_companion_osaxen.html

tell application "Music"
    try
        set the_tracks to the selection
        repeat with a_track in the_tracks
            set the_old_name to name of a_track as string
            set the_new_name to titlecase the_old_name
            set the name of a_track to the_new_name
            log the_old_name
            log the_new_name
        end repeat
    on error
        set the_tracks to the selection
        repeat with a_track in the_tracks
            set the_old_name to name of a_track as string
            set the_new_name to titlecase the_old_name
            set the name of a_track to the_new_name
            log the_old_name
            log the_new_name
        end repeat
    end try
end tell

而且我希望能够更改 string/title 中单个元素的大小写。特别是将罗马数字更改为全部大写,在此示例中查找“Iv”。并将其更改为“IV”。:

来自: G小调第八大协奏曲,作品。 6、《圣诞协奏曲》:Iv.活泼

至:G 小调第 8 号大协奏曲,作品。 6、《圣诞协奏曲》:IV.活泼

如有任何帮助,我们将不胜感激。谢谢!

此处理程序将 I 到 IX 后跟句点的所有罗马字符替换为其对应的大写字母。它使用来自 Foundation 框架

的强大 API
use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

on uppercaseRomanCharacters(theText)
    set cocoaString to current application's NSString's stringWithString:theText
    set romanRange to cocoaString's rangeOfString:"(I{1,3}|IX|IV|VI{0,3})\." options:1025
    if romanRange's location < cocoaString's |length|() then
        set substring to cocoaString's substringWithRange:romanRange
        return (cocoaString's stringByReplacingCharactersInRange:romanRange withString:(substring's uppercaseString())) as text
    end if
    return theText
end uppercaseRomanCharacters

set theString to "Concerto Grosso No. 8 in G Minor, Op. 6, \"Christmas Concerto\": iv. Vivace"
set newName to uppercaseRomanCharacters(theString)

您可以在循环中使用它

repeat with a_track in the_tracks
    set the_old_name to name of a_track -- as string is redundant
    set the_new_name to my uppercaseRomanCharacters(the_old_name)
    set the name of a_track to the_new_name
    log the_old_name
    log the_new_name
end repeat

处理程序必须位于脚本顶层的某处。

注意:1025 是选项的整数值 NSCaseInsensitiveSearch | NSRegularExpressionSearch