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
#########################

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom