0

How would I write a script to analyze strings in Applescript (or other scripting program for mac)? Example: scan text file for "I love eating", copy subsequent text, end at ".", so that if my file was "I love eating apples. I love eating cherries. I love eating grapes, pecans, and peaches." it would return "apples cherries grapes, pecans, and peaches"

1 Answer 1

1

The usual suspect for processing text in AppleScript is the built-in, global property text item delimiters. You can use it to both break a single string into multiple pieces (when using the text items … of reference form), select range endpoints (when using text item N in the text … of reference form), and join several pieces into a single string (when coercing a list to a string).

to pickText(str, startAfter, stopBefore)
    set pickedText to {}
    set minLength to (length of startAfter) + (length of stopBefore)
    repeat while length of str is greater than or equal to minLength
        -- look for the start marker
        set text item delimiters to startAfter
        -- finish if it is not there
        if (count of text items of str) is less than 2 then exit repeat
        -- drop everything through the end of the first start marker
        set str to text from text item 2 to end of str

        -- look for the end marker
        set text item delimiters to stopBefore
        -- finish if it is not there
        if (count of text items of str) is less than 2 then exit repeat
        -- save the text up to the end marker
        set end of pickedText to text item 1 of str

        -- try again with what is left after the first end marker
        set str to text from text item 2 to end of str
    end repeat
    set text item delimiters to " "
    pickedText as string
end pickText

-- process some “hard coded” text
set s to "I love eating apples. I love eating cherries. I love eating grapes, pecans, and peaches."
pickText(s, "I love eating ", ".") --> "apples cherries grapes, pecans, and peaches"


-- process text from a file
set s to read file ((path to desktop folder as string) & "Untitled.txt")
pickText(s, "I love eating ", ".")
2
  • Stupid question, though: how would I create text item deliminators that included quote marks? Obviously """ wouldn't work- Jan 15, 2011 at 7:29
  • 1
    You can escape the quote character using the backslash: "\""
    – NSGod
    Jan 15, 2011 at 22:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .