Find and Replace in AppleScript

感情迁移 提交于 2019-12-21 17:49:40

问题


I'm currently writing a super simple script and I need to find and replace text in a variable (specifically in the path of the items dropped onto the applescript.) Here is what I have currently:

    on open {dropped_items}
    tell application "Finder" to set filePathLong to the POSIX path of dropped_items as text


on replaceText(find, replace, subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to find
    set subject to text items of subject

    set text item delimiters of AppleScript to replace
    set subject to "" & subject
    set text item delimiters of AppleScript to prevTIDs

    return subject
end replaceText

get replaceText("/mpc/mayors1", "/ifs/disk1", filePathLong)




display dialog subject

end open

(excluding irrelevant code and adding a dialog to verify it worked)

That "on replaceText..." block I got from searching Stack Overflow for the title of this post. My problem is that when I try to compile it tells me it expected an "end" but found an "on." I'm assuming it wants me to end my open before I can "on replaceText" but I don't want to do that. Any ideas as to what I could do to get it to work? Sorry if this is very simple, I'm pretty new to AppleScript.

I understand I could just chop off the first twelve characters and then add "/ifs/disk1" to the beginning of the string but I want to know why this isn't working in case this happens again.


回答1:


You can't place a handler within another (explicit) handler. Made some other corrections as well.

on open dropped_items
    repeat with anItem in dropped_items
        set filePathLong to anItem's POSIX path
        set mySubject to replaceText("/mpc/mayors1", "/ifs/disk1", filePathLong)
        display dialog mySubject
    end repeat
end open


on replaceText(find, replace, subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to find
    set subject to text items of subject

    set text item delimiters of AppleScript to replace
    set subject to subject as text
    set text item delimiters of AppleScript to prevTIDs

    return subject
end replaceText



回答2:


You can follow this https://github.com/abbeycode/AppleScripts/blob/master/Scripts/Libraries/Strings.applescript

on replace_text(this_text, search_string, replacement_string)
    set prevTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to the search_string
    set the item_list to every text item of this_text
    set AppleScript's text item delimiters to the replacement_string
    set this_text to the item_list as string
    set AppleScript's text item delimiters to prevTIDs
    return this_text
end replace_text


来源:https://stackoverflow.com/questions/28115085/find-and-replace-in-applescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!