AppleScript: Index of substring in string
I want to create a fun开发者_如何学运维ction 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 "
)
set s to "Today is my birthday"
set AppleScript's text item delimiters to "my"
text item 1 of s
--> "Today is "
The built-in offset
command should do it:
set s to "Today is my birthday"
log text 1 thru ((offset of "my" in s) - 1) of s
--> "Today is "
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
精彩评论