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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1716440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:33:37  来源:igfitidea点击:

AppleScript: Index of substring in string

stringfunctionmethodsapplescriptsubstring

提问by Alexsander Akers

I want to create a function that returns a substring of a specific string from the beginning of said string up to but not including the start of another specific string. Ideas?

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



So something like:

所以像:

substrUpTo(theStr, subStr)

so if I inputted substrUpTo("Today is my birthday", "my"), it would return a substring of the first argument up to but not including where the second argument begins. (i.e. it would return "Today is ")

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

回答by has

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

回答by duozmo

The built-in offsetcommand should do it:

内置offset命令应该这样做:

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

回答by Philip Regan

Probably a bit kludgey, but it gets the job done...

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

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