AppleScript Regular Expression

[文字列置換]NSRegularExpressionSearch

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableString : a reference to refMe's NSMutableString

property refNSRegularExpressionSearch : a reference to refMe's NSRegularExpressionSearch

property refNSNotFound : a reference to 9.22337203685477E+18 + 5807


set strOriginalText to "美しい日本語,美しい日本酒,美しい日本画,美しい日本髪"

###テキストをNSMutableStringに
##まずは初期化して
set ocidSampleText to refNSMutableString's alloc()'s initWithCapacity:0

###テキストをNSMutableStringにセット
ocidSampleText's setString:strOriginalText
log ocidSampleText as text
log className() of ocidSampleText as text


###NSMutableString文字列からRangeを作成
set ocidNSRange to ocidSampleText's rangeOfString:ocidSampleText
log ocidNSRange
log class of ocidNSRange

###置き換え
ocidSampleText's replaceOccurrencesOfString:("(日本).") withString:("$1食") options:(refNSRegularExpressionSearch) range:ocidNSRange
log ocidSampleText as text
log ocidSampleText's className() as text



return

|

[文字列置換]NSRegularExpressionSearch(正規表現)

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions


property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSMutableString : a reference to refMe's NSMutableString

property refNSRegularExpressionSearch : a reference to refMe's NSRegularExpressionSearch

property refNSNotFound : a reference to 9.22337203685477E+18 + 5807


set strOriginalText to "美しい日本語,美しい日本酒,美しい日本画,美しい日本髪"

###テキストをNSMutableStringに
##まずは初期化して
set ocidSampleText to refNSMutableString's alloc()'s initWithCapacity:0

###テキストをNSMutableStringにセット
ocidSampleText's setString:strOriginalText
log ocidSampleText as text
log className() of ocidSampleText as text


###NSMutableString文字列からRangeを作成
set ocidNSRange to ocidSampleText's rangeOfString:ocidSampleText
log ocidNSRange
log class of ocidNSRange

###置き換え
ocidSampleText's replaceOccurrencesOfString:("(日本).") withString:("$1食") options:(refNSRegularExpressionSearch) range:ocidNSRange
log ocidSampleText as text
log ocidSampleText's className() as text



return

|

[matchesInString]文字の置換(regularExpressionWithPattern)

サンプルが悪いか…苦笑


#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


set strOriginalText to "美しい日本語,美しい日本酒,美しい日本画,美しい日本髪"

###NSStringにして
set ocidText to refMe's NSString's stringWithString:strOriginalText
###文字数を数えて
set numTextLength to ocidText's |length|()
###文字列全部のレンジを作成
set ocidTextRange to {location:0, |length|:numTextLength}
####設定:正規表現の検索パターン
set strPattern to "日本."
####オプションNSRegularExpressionOptions
set ocidOption to 0 as integer
###正規表現を定義
set listRegularExpression to refMe's NSRegularExpression's regularExpressionWithPattern:strPattern options:ocidOption |error|:(reference)
###戻り値からNSRegularExpressionを取得(面倒なら--> |error|:(missing value)を利用
set ocidRegularExpression to (item 1 of listRegularExpression)
###処理実行
set ocidResults to ocidRegularExpression's matchesInString:ocidText options:ocidOption range:ocidTextRange
###戻り値の数を数える
set numResults to (count of ocidResults) as integer
log numResults
-->文字の出現回数
-->(*4*)


repeat with itemResults in ocidResults
    log className() of itemResults as text
    ###対象のNSSimpleRegularExpressionCheckingResultのレンジ
    set recordRange to itemResults's range
    log recordRange as record
    -->このレンジに対象の文字列があるので、後で置き換える
    -->(*location:x, length:3*)
    log itemResults's resultType as integer
    -->(*1024*)=(NSTextCheckingTypeRegularExpression)
    log itemResults's numberOfRanges as integer
    -->(*1*)
    ##該当するテキスト部
    log (ocidText's substringWithRange:recordRange) as text
    ###レンジで置換
    set ocidText to (ocidText's stringByReplacingCharactersInRange:recordRange withString:"日本食")
    
    
end repeat

log ocidText as text
-->(*美しい日本食,美しい日本食,美しい日本食,美しい日本食*)

return

#アルファベットの大文字と小文字の区別無し
log refMe's NSRegularExpressionCaseInsensitive as integer
-->(*1*)
#スペースと#コメントを無視
log refMe's NSRegularExpressionAllowCommentsAndWhitespace as integer
-->(*2*)
##メタ文字無視
log refMe's NSRegularExpressionIgnoreMetacharacters as integer
-->(*4*)
##ドット=.が改行コードにもマッチ
log refMe's NSRegularExpressionDotMatchesLineSeparators as integer
-->(*8*)
#行頭行末の^$が各行マッチ
log refMe's NSRegularExpressionAnchorsMatchLines as integer
-->(*16*)
##\nだけが改行コード 他の改行コードはマッチの対象
log refMe's NSRegularExpressionUseUnixLineSeparators as integer
-->(*32*)
##ユニコード式の文字区切り \b
log refMe's NSRegularExpressionUseUnicodeWordBoundaries as integer
-->(*64*)

|

[NSRegularExpression]文字の出現数を取得

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application


set strOriginalText to "美しい日本語,美しい日本"

###NSStringにして
set ocidText to refMe's NSString's stringWithString:strOriginalText
###文字数を数えて
set numTextLength to ocidText's |length|()
###文字列全部のレンジを作成
set ocidTextRange to {location:0, |length|:numTextLength}
####設定:検索パターン
set strPattern to "美"
####オプションNSRegularExpressionOptions
set ocidOption to 0 as integer
###正規表現を定義
set listRegularExpression to refMe's NSRegularExpression's regularExpressionWithPattern:strPattern options:ocidOption |error|:(reference)
###戻り値からNSRegularExpressionを取得(面倒なら--> |error|:(missing value)を利用
set ocidRegularExpression to (item 1 of listRegularExpression)
###処理実行
set ocidResults to ocidRegularExpression's matchesInString:ocidText options:ocidOption range:ocidTextRange
###戻り値の数を数える
set numResults to (count of ocidResults) as integer
log numResults
-->文字の出現回数
(*2*)


return

####NSRegularExpressionOptions 無しは0

log refMe's NSRegularExpressionCaseInsensitive as integer
-->(*1*)
log refMe's NSRegularExpressionAllowCommentsAndWhitespace as integer
-->(*2*)
log refMe's NSRegularExpressionIgnoreMetacharacters as integer
-->(*4*)
log refMe's NSRegularExpressionDotMatchesLineSeparators as integer
-->(*8*)
log refMe's NSRegularExpressionAnchorsMatchLines as integer
-->(*16*)
log refMe's NSRegularExpressionUseUnixLineSeparators as integer
-->(*32*)
log refMe's NSRegularExpressionUseUnicodeWordBoundaries as integer
-->(*64*)

|

[regular expression]正規表現ファイル名系

#########################
#####小文字を大文字に

set strFileName to "aaaaaaa99999cccccc.txt"

set strCommandText to ("echo \"" & strFileName & "\" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'") as text
set strResponse to (do shell script strCommandText) as text

log strResponse
-->(*AAAAAAA99999CCCCCC.TXT*)

#########################
#####ハイフンを入れる

set strFileName to "aaaaaaa99999cccccc.txt"

set strCommandText to ("echo \"" & strFileName & "\" | sed -e 's/\\(.[a-zA-Z]\\)\\([0-9].\\)/\\1-\\2/g'") as text
set strResponse to (do shell script strCommandText) as text

log strResponse
-->(*aaaaaaa-99999cccccc.txt*)

#########################
#####ハイフンを入れる

set strFileName to "aaaaaaa99999cccccc.txt"

set strCommandText to ("echo \"" & strFileName & "\" | sed -e 's/\\(.[0-9]\\)\\([a-zA-Z].\\)/\\1-\\2/g'") as text
set strResponse to (do shell script strCommandText) as text

log strResponse
-->(*aaaaaaa99999-cccccc.txt*)

#####ハイフンを入れる

|

[NSStringCompareOptions] NSLiteralSearch リテラル文字通りに検索

一番使い勝手のいいやつ 
正規表現使わないなら基本はこれ

NSStringCompareOptions
NSCaseInsensitiveSearch1
NSLiteralSearch2
NSBackwardsSearch4
NSAnchoredSearch8
NSNumericSearch64
NSDiacriticInsensitiveSearch128
NSWidthInsensitiveSearch256
NSForcedOrderingSearch512
NSRegularExpressionSearch1024





#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSMutableString : a reference to objMe's NSMutableString


property objNSLiteralSearch : a reference to objMe's NSLiteralSearch


property objNSNotFound : a reference to 9.22337203685477E+18 + 5807


set strSampleText to "美しい日本語の\nオープン\\タイプフォント"

###テキストをNSMutableString
##まずは初期化して
set ocidSampleText to objNSMutableString's alloc()'s initWithCapacity:0

###テキストをNSMutableStringにセット
ocidSampleText's setString:strSampleText
log ocidSampleText as text
log className() of ocidSampleText as text


###NSMutableString文字列からRangeを作成
set ocidNSRange to ocidSampleText's rangeOfString:ocidSampleText
log ocidNSRange
log class of ocidNSRange

###置き換え
ocidSampleText's replaceOccurrencesOfString:("\n") withString:("\t") options:(objNSLiteralSearch) range:ocidNSRange
log ocidSampleText as text
log ocidSampleText's className() as text

###置き換え
ocidSampleText's replaceOccurrencesOfString:("\\") withString:("") options:(objNSLiteralSearch) range:ocidNSRange
log ocidSampleText as text
log ocidSampleText's className() as text

return


#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

[NSStringCompareOptions] NSRegularExpressionSearch 正規表現

正規表現で対象の文字をRangeの内から検索
正規表現を使って
改行やタブといった制御文字等を削除できます

NSStringCompareOptions
NSCaseInsensitiveSearch1
NSLiteralSearch2
NSBackwardsSearch4
NSAnchoredSearch8
NSNumericSearch64
NSDiacriticInsensitiveSearch128
NSWidthInsensitiveSearch256
NSForcedOrderingSearch512
NSRegularExpressionSearch1024





#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSMutableString : a reference to objMe's NSMutableString

property objNSRegularExpressionSearch : a reference to objMe's NSRegularExpressionSearch


property objNSNotFound : a reference to 9.22337203685477E+18 + 5807


set strSampleText to "美しい日本語の\nオープンタイプフォント"

###テキストをNSMutableString
##まずは初期化して
set ocidSampleText to objNSMutableString's alloc()'s initWithCapacity:0

###テキストをNSMutableStringにセット
ocidSampleText's setString:strSampleText
log ocidSampleText as text
log className() of ocidSampleText as text


###NSMutableString文字列からRangeを作成
set ocidNSRange to ocidSampleText's rangeOfString:ocidSampleText
log ocidNSRange
log class of ocidNSRange

###置き換え
ocidSampleText's replaceOccurrencesOfString:("\n") withString:("") options:(objNSRegularExpressionSearch) range:ocidNSRange
log ocidSampleText as text
log ocidSampleText's className() as text



return


#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

その他のカテゴリー

Acrobat Acrobat Annotation Acrobat Dialog Acrobat Form Acrobat JS Acrobat Open Acrobat Plugin Acrobat python Acrobat Reader Acrobat Sequ Acrobat Stamps Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin System Information Admin Tools Admin Users Admin Volumes Adobe Apple AppleScript AppleScript Guide AppleScript Accessibility AppleScript AppKit AppleScript Applications AppleScript AppStore AppleScript Archive AppleScript Attributes AppleScript Automator AppleScript AVAsset AppleScript AVconvert AppleScript AVFoundation AppleScript AVURLAsset AppleScript BackUp AppleScript Barcode AppleScript Bash AppleScript Basic AppleScript Basic Path AppleScript Bluetooth AppleScript BOX AppleScript Browser AppleScript Calendar AppleScript CD/DVD AppleScript Choose AppleScript Chrome AppleScript CIImage AppleScript CloudStorage AppleScript Color AppleScript com.apple.LaunchServices.OpenWith AppleScript Console AppleScript Contacts AppleScript CotEditor AppleScript CURL AppleScript current application AppleScript Date&Time AppleScript delimiters AppleScript Desktop AppleScript Device AppleScript Disk AppleScript do shell script AppleScript Dock AppleScript DropBox AppleScript eMail AppleScript Encode Decode AppleScript Error AppleScript EXIFData AppleScript ffmpeg AppleScript File AppleScript Finder AppleScript Firefox AppleScript Folder AppleScript Fonts AppleScript GIF AppleScript HTML AppleScript Icon AppleScript Illustrator AppleScript Image Events AppleScript Image2PDF AppleScript ImageOptim Applescript iWork AppleScript Javascript AppleScript Jedit AppleScript Json AppleScript Label AppleScript List AppleScript locationd AppleScript LRC AppleScript LSSharedFileList AppleScript m3u8 AppleScript MakePDF AppleScript Map AppleScript Math AppleScript Microsoft AppleScript Microsoft Edge AppleScript Microsoft Excel AppleScript Mobileconfig AppleScript Mouse AppleScript Movie AppleScript Music AppleScript NetWork AppleScript Notes AppleScript NSArray AppleScript NSBitmapImageRep AppleScript NSBundle AppleScript NSCFBoolean AppleScript NSCharacterSet AppleScript NSColor AppleScript NSColorList AppleScript NSData AppleScript NSDictionary AppleScript NSError AppleScript NSEvent AppleScript NSFileAttributes AppleScript NSFileManager AppleScript NSFont AppleScript NSFontManager AppleScript NSImage AppleScript NSIndex AppleScript NSKeyedArchiver AppleScript NSKeyedUnarchiver AppleScript NSLocale AppleScript NSMutableArray AppleScript NSMutableDictionary AppleScript NSMutableString AppleScript NSNotFound AppleScript NSNumber AppleScript NSOpenPanel AppleScript NSPasteboard AppleScript NSPDFImageRep AppleScript NSpoint AppleScript NSPredicate AppleScript NSRange AppleScript NSRegularExpression AppleScript NSRunningApplication AppleScript NSScreen AppleScript NSSize AppleScript NSString AppleScript NSStringCompareOptions AppleScript NSTask AppleScript NSTimeZone AppleScript NSURL AppleScript NSURL File AppleScript NSURLBookmark AppleScript NSURLComponents AppleScript NSURLResourceKey AppleScript NSUserDefaults AppleScript NSUUID AppleScript NSView AppleScript NSWorkspace AppleScript Numbers AppleScript OAuth AppleScript ObjC AppleScript OneDrive AppleScript Osax AppleScript PDF AppleScript PDFAnnotationWidget AppleScript PDFContext AppleScript PDFDisplayBox AppleScript PDFDocumentPermissions AppleScript PDFKit AppleScript PDFnUP AppleScript PDFOutline AppleScript Photos AppleScript Photoshop AppleScript Plist System Events AppleScript PostScript AppleScript prefPane AppleScript Preview AppleScript Python AppleScript QR AppleScript QR Decode AppleScript QuickLook AppleScript QuickTime AppleScript record AppleScript Regular Expression AppleScript Reminders AppleScript ReName AppleScript Repeat AppleScript RTF AppleScript Safari AppleScript SaveFile AppleScript ScreenCapture AppleScript ScreenSaver AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript Sort AppleScript Sound AppleScript Spotlight AppleScript SRT AppleScript StandardAdditions AppleScript stringByApplyingTransform AppleScript System Events AppleScript System Settings AppleScript TemporaryItems AppleScript Terminal AppleScript Text AppleScript Text CSV AppleScript Text TSV AppleScript TextEdit AppleScript Translate AppleScript Trash AppleScript Twitter AppleScript UI AppleScript Unit Conversion AppleScript UTType AppleScript valueForKeyPath AppleScript Video AppleScript VisionKit AppleScript Visual Studio Code AppleScript webarchive AppleScript webp AppleScript Wifi AppleScript XML AppleScript XML EPUB AppleScript XML OPML AppleScript XML Plist AppleScript XML RSS AppleScript XML SVG AppleScript XML TTML AppleScript XML webloc AppleScript YouTube AppleScript Zero Suppress Applications Barcode OnLine Tools CityCode Design iPhone List Logs lsappinfo Memo Music perl PlistBuddy pluginkit postalcode ReadMe SF Symbols character id SF Symbols Entity sips Skype Slack sqlite TCC Tools Typography Video Wacom zoom