AppleScript:字符串中子字符串的索引

时间:2009-11-11 16:36:44

标签: string function methods applescript substring

我想创建一个函数,该函数从所述字符串的开头返回特定字符串的子字符串,但不包括另一个特定字符串的开头。想法?


类似于:

substrUpTo(theStr, subStr)

所以如果我输入substrUpTo("Today is my birthday", "my"),它将返回第一个参数的子字符串,但不包括第二个参数的开始位置。 (即它会返回"Today is "

3 个答案:

答案 0 :(得分:9)

set s to "Today is my birthday"
set AppleScript's text item delimiters to "my"
text item 1 of s
--> "Today is "

答案 1 :(得分:4)

内置offset命令应该这样做:

set s to "Today is my birthday"
log text 1 thru ((offset of "my" in s) - 1) of s
--> "Today is "

答案 2 :(得分:0)

可能有点笨拙,但它完成了工作......

property kSourceText : "Today is my birthday"
property kStopText : "my"

set newSubstring to SubstringUpToString(kSourceText, kStopText)

return newSubstring -- "Today is "

on SubstringUpToString(theString, subString) -- (theString as string, subString as string) as string

    if theString does not contain subString then
        return theString
    end if

    set theReturnString to ""

    set stringCharacterCount to (get count of characters in theString)
    set substringCharacterCount to (get count of characters in subString)
    set lastCharacter to stringCharacterCount - substringCharacterCount

    repeat with thisChar from 1 to lastCharacter
        set startChar to thisChar
        set endChar to (thisChar + substringCharacterCount) - 1
        set currentSubstring to (get characters startChar thru endChar of theString) as string
        if currentSubstring is subString then
            return (get characters 1 thru (thisChar - 1) of theString) as string
        end if
    end repeat

    return theString
end SubstringUpToString