Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

シンプルな文字置換

Posted on 9月 13 by Takaaki Naganoya

AppleScriptで文字置換を行う場合には、いくつかの方法があります。

①text item delimitersを利用する

AppleScriptの登場以来、利用されてきた方法です。AppleScriptの処理系では最速といってよい方法ですが、複数の箇所を一気に置換するのでやや過剰なのと処理方法が独特なので敬遠する人もいるようです。

また、処理対象の文字列のサイズが数Mバイト以上になると、処理が終了しなかったりします。巨大な文字列の置換には⑤が推奨されます。CotEditorのようなScriptableなテキストエディタの機能を利用するのもアリでしょう。

AppleScript名:文字置換(最短).scpt
set origText to "abcdefg"
set targStr to "de"
set repStr to "xx"

set a to repChar(origText, targStr, repStr) of me
–> "abcxxfg"

–Written By Philip Aker
–文字置換ルーチン
on repChar(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

★Click Here to Open This Script 

②shellコマンドを利用する

do shell scriptコマンド経由で置換コマンドを利用する方法です。Mac OS X以降後に利用できるようになったものですが、日本語に対して正確に置換できるのか不安が残るので、個人的にはあまり積極的には利用していません。

③OSAXを利用する

macOS 10.15でサードパーティのOSAX(Scripting Additions)が廃止されたため、現在では利用できません。

④AppleScript Librariesを利用する

Shane StanleyのRegexAndStuffLibなどのライブラリを用いて正規表現を用いた文字置換を利用するものです。

⑤Cocoaの機能を利用する

Cocoaの機能を呼び出して文字置換を行うものです。いくつも利用できる機能があります。正規表現を使うものなど、お好きなものを利用してください。

AppleScript名:ASOCで文字置換5.scptd
— Created 2015-06-30 by Takaaki Naganoya
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set a to "あいうえお++かきくけこ"
set b to cleanUpText(a, "+", "●")
–> "あいうえお●●かきくけこ"

on cleanUpText(someText, targStr, repStr)
  set theString to current application’s NSString’s stringWithString:someText
  
set targString to current application’s NSString’s stringWithString:targStr
  
set repString to current application’s NSString’s stringWithString:repStr
  
  
set theString to theString’s stringByReplacingOccurrencesOfString:targString withString:repString options:(current application’s NSRegularExpressionSearch) range:{location:0, |length|:length of someText}
  
return theString as text
end cleanUpText

★Click Here to Open This Script 

これらに加えて、もっと簡単な方法がないかと探してみたら、

⑥offset ofで文字列検索して置換を行う

offset ofで置換対象の文字列を検索して置換を行います。オリジナル文字列に対して置換対象の文字列の位置が「冒頭ではない」「末尾ではない」という条件がそろっていて、かつ置換対象が0ないし1回しか対象文字列中に存在しないことが事前に分かりきっている場合にのみ使えます。

set urlData to "https://www.amazon.co.jp/gp/css/summary/print.html/ref=oh_aui_ajax_invoice"

set anOffset to offset of "/gp/" in urlData
set newURL to (text 1 thru (anOffset + (length of "/gp/") – 1) of urlData) & "legacy" & (text (anOffset + (length of "/gp/") – 1) thru -1 of urlData)

–> "https://www.amazon.co.jp/gp/legacy/css/summary/print.html/ref=oh_aui_ajax_invoice"

★Click Here to Open This Script 

このぐらいで使えますが、本当にすべてのパターンを利用するには、場合分けしつつ書く必要があります。シンプルなはずなのに、シンプルになっていないという。

AppleScript名:単純文字置換.scpt
set urlData1 to "https://www.amazon.co.jp/gp/css/summary/print.html/ref=oh_aui_ajax_invoice"
set newURL1 to replaceOne(urlData1, "/gp/", "/gp/legacy/") of me
–> "https://www.amazon.co.jp/gp/legacy/css/summary/print.html/ref=oh_aui_ajax_invoice"

set urlData2 to "https://www.amazon.co.jp/css/summary/print.html/ref=oh_aui_ajax_invoice/gp/"
set newURL2 to replaceOne(urlData2, "/gp/", "/gp/legacy/") of me
–> "https://www.amazon.co.jp/css/summary/print.html/ref=oh_aui_ajax_invoice/gp/legacy/"

set urlData3 to "https://www.amazon.co.jp/css/summary/print.html/ref=oh_aui_ajax_invoice/gp/"
set newURL3 to replaceOne(urlData3, "https://", "http://") of me
–> "http://www.amazon.co.jp/css/summary/print.html/ref=oh_aui_ajax_invoice/gp/"

on replaceOne(origStr as string, targStr as string, repStr as string)
  set anOffset to offset of targStr in origStr
  
if anOffset = 0 then return origStr
  
set {aLen, bLen} to {length of origStr, length of targStr}
  
  
if anOffset + bLen > aLen then
    –置換対象文字が末尾にある場合
    
set newStr1 to (text 1 thru (anOffset – 1) of origStr)
    
set newStr2 to ""
  else if anOffset = 1 then
    –置換対象文字が先頭にある場合
    
set newStr2 to (text (anOffset + ((length of targStr))) thru -1 of origStr)
    
set newStr1 to ""
  else
    –通常パターン
    
set newStr1 to (text 1 thru (anOffset – 1) of origStr)
    
set newStr2 to (text (anOffset + ((length of targStr))) thru -1 of origStr)
  end if
  
return newStr1 & repStr & newStr2
end replaceOne

★Click Here to Open This Script 

(Visited 1 times, 1 visits today)
Posted in Text | Tagged 13.0savvy 14.0savvy 15.0savvy 26.0savvy | Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • Numbersで選択範囲のセルの前後の空白を削除
  • macOS 15でも変化したText to Speech環境
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • Script Debuggerの開発と販売が2025年に終了
  • 【続報】macOS 15.5で特定ファイル名パターンのfileをaliasにcastすると100%クラッシュするバグ
  • KagiのWebブラウザ、Orion
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • macOS 26, Tahoe
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 15 リモートApple Eventsにバグ?
  • NSObjectのクラス名を取得 v2.1
  • macOS 15:スクリプトエディタのAppleScript用語辞書を確認できない
  • 2024年に書いた価値あるAppleScript
  • 有害ではなくなっていたSpaces
  • Pixelmator Proがv3.6.8でHDR画像をサポート
  • Xcode上のAppleScriptObjCのプログラムから、Xcodeのログ欄へのメッセージ出力を実行
  • (確認中)AppleScript Dropletのバグっぽい動作が解消?
  • AVSpeechSynthesizerで読み上げテスト
  • AppleScript Dropletのバグっぽい動作が「復活」(macOS 15.5β)
  • 指定フォルダ以下の画像のMD5チェックサムを求めて、重複しているものをピックアップ

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (201) 14.0savvy (156) 15.0savvy (145) CotEditor (66) Finder (52) Keynote (119) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Pixelmator Pro (20) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • process
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • Scripting Additions
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2025年9月
  • 2025年8月
  • 2025年7月
  • 2025年6月
  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC