2017-03-14 1 views
0

나는이 스크립트를 가지고 있지만 나는 그렇게 만 일치하는 검색 문자열의 첫 번째 항목을 대체 변경하려면 : 나는 사방 검색했습니다Applescript에서 일치하는 검색 문자열의 첫 번째 항목 만 바꾸려면 어떻게해야합니까?

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

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

하지만 성공이 없었다. 나는 어떤 도움을 주셔서 감사합니다.

답변

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 
+0

이 훨씬 더하지만 여전히 간단한/짧은 해결책이 될 것이다 바랍니다. 나는 내 대답을 삭제했다. – vadian

+0

이것은 효과가 있고 짧습니다. 그러나 문자열의 마지막 문자를 바꿀 때 여전히 문제가 있습니다. findAndReplaceFirstOccurrenceInText ("susan", "an", "1") - "sus1n"을 반환합니다. – treemok

+0

내 감시가 지금 고정되었습니다. – foo

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