如何仅替换Applescript中第一次匹配的搜索字符串?

时间:2017-03-14 06:08:29

标签: applescript

我有这个脚本,但我想改变所以它只替换第一次匹配的搜索字符串:

on findAndReplaceInText(theText, theSearchString, theReplacementString)
	set AppleScript's text item delimiters to theSearchString
	set theTextItems to every text item of theText
	set AppleScript's text item delimiters to theReplacementString
	set theText to theTextItems as string
	set AppleScript's text item delimiters to ""
	return theText
end findAndReplaceInText

findAndReplaceInText("susan", "s", "t") -- returns "tutan" but I want "tusan"

我一直在寻找,但没有成功。我将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:2)

没有任何错误处理:

to findAndReplaceFirstOccurrenceInText(theText, theSearchString, theReplacementString)
    set AppleScript's text item delimiters to theSearchString
    return text item 1 of theText & theReplacementString & text (text item 2) thru (text item -1) of theText
end findAndReplaceFirstOccurrenceInText

答案 1 :(得分:0)

我更新了vadians代码,以便在替换最后一个字符时修复错误。但我仍然希望有一个更简单/更短的解决方案:

on findAndReplaceFirstOccurrenceInText(theText, theSearchString, theReplacementString)
set theOffset to offset of theSearchString in theText
if theOffset is 0 then
    return theText
else if theOffset is 1 then
    tell theText to return theReplacementString & text (theOffset + (length of theSearchString)) thru -1
else if theOffset is length of theText then
    tell theText to return text 1 thru (theOffset - 1) & theReplacementString
else
    tell theText to return text 1 thru (theOffset - 1) & theReplacementString & text (theOffset + (length of theSearchString)) thru -1
end if

结束findAndReplaceFirstOccurrenceInText