10

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


所以像:

substrUpTo(theStr, subStr)

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

4

3 回答 3

13
set s to "Today is my birthday"
set AppleScript's text item delimiters to "my"
text item 1 of s
--> "Today is "
于 2009-11-15T10:47:54.683 回答
9

内置offset命令应该这样做:

set s to "Today is my birthday"
log text 1 thru ((offset of "my" in s) - 1) of s
--> "Today is "
于 2013-05-29T21:27:40.700 回答
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
于 2009-11-11T21:22:37.180 回答