如何仅替换Applescript中匹配搜索字符串的第一个匹配项?
我有此脚本,但我想更改,使其仅替换匹配搜索字符串的第一个匹配项: 查找和替换文本时的如何仅替换Applescript中匹配搜索字符串的第一个匹配项?,applescript,Applescript,我有此脚本,但我想更改,使其仅替换匹配搜索字符串的第一个匹配项: 查找和替换文本时的(文本、搜索字符串、替换字符串) 将AppleScript的文本项分隔符设置为搜索字符串 将文本项设置为文本的每个文本项 将AppleScript的文本项分隔符设置为替换字符串 将文本设置为字符串形式的文本项 将AppleScript的文本项分隔符设置为“” 返回文本 end FindReplaceIntext findAndReplaceInText(“susan”、“s”、“t”)--返回“tutan”,但
(文本、搜索字符串、替换字符串)
将AppleScript的文本项分隔符设置为搜索字符串
将文本项设置为文本的每个文本项
将AppleScript的文本项分隔符设置为替换字符串
将文本设置为字符串形式的文本项
将AppleScript的文本项分隔符设置为“”
返回文本
end FindReplaceIntext
findAndReplaceInText(“susan”、“s”、“t”)--返回“tutan”,但我希望“tusan”
更新Vadian代码以修复替换最后一个字符时的错误。但我仍然希望有一个更简单/更短的解决方案:
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
end FindReplaceFirstOccurrenceIntext我将更新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
end FindReplaceFirstOccurrenceIntext无任何错误处理:
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
无任何错误处理:
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
这个有效,而且更短。但是,当我想替换字符串的最后几个字符时,仍然存在一个问题:findAndReplaceFirstOccurrenceInText(“susan”、“an”、“1”)--返回“sus1n”我的疏忽,现在已修复。这有效,而且更短。但是,当我想替换字符串的最后几个字符时,仍然存在一个问题:findAndReplaceFirstOccurrenceInText(“susan”、“an”、“1”)——返回“sus1n”我的疏忽,现已修复。