NSRegularExpression

[正規表現]リストAからリストBの項目を削除する



ダウンロード - mactchdel.zip



202411110310481_1400x1460
AppleScript サンプルコード

【スクリプトエディタで開く】 |

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.6"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011property refMe : a reference to current application
012
013
014#ファイルリスト
015#元データ
016set strSummaryFileName to ("メールアドレス.txt") as text
017#その中から削除したいリスト
018set strModifyFileName to ("削除アドレス.txt") as text
019#生成物保存先
020set strSaveFileName to ("出力.txt") as text
021
022
023############################
024#このスクリプトのパス
025set aliasPathToMe to (path to me) as alias
026set strPathToMe to (POSIX path of aliasPathToMe) as text
027set ocidPathToMeStr to refMe's NSString's stringWithString:(strPathToMe)
028set ocidPathToMe to ocidPathToMeStr's stringByStandardizingPath()
029set ocidPathToMeURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidPathToMe) isDirectory:false)
030set ocidContainerDirPathURL to ocidPathToMeURL's URLByDeletingLastPathComponent()
031
032############################
033#URL
034set ocidSummaryFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(strSummaryFileName) isDirectory:(false)
035set ocidModifyFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(strModifyFileName) isDirectory:(false)
036set ocidSaveFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(strSaveFileName) isDirectory:(false)
037
038############################
039#ファイル読み込み
040set ocidOption to (refMe's NSUTF8StringEncoding)
041set listResponse to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidSummaryFilePathURL) encoding:(ocidOption) |error| :(reference)
042set ocidSummaryString to (item 1 of listResponse)
043#改行をUNIXに強制
044set ocidSummaryString to (ocidSummaryString's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
045set ocidSummaryString to (ocidSummaryString's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
046#最後の改行を調べて
047set boolSuffixLF to (ocidSummaryString's hasSuffix:("\n")) as boolean
048#最後の文字が改行なら削除しておく
049if boolSuffixLF is true then
050  #文字数のレンジ
051  set ocidLegth to ocidSummaryString's |length|()
052  set ocidSummaryString to ocidSummaryString's substringToIndex:(ocidLegth - 1)
053end if
054#行数を数えておく=件数
055set ocidSummaryArray to ocidSummaryString's componentsSeparatedByString:("\n")
056set numCntSummaryArray to ocidSummaryArray's |count|()
057
058#ファイル読み込み
059set listResponse to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidModifyFilePathURL) encoding:(ocidOption) |error| :(reference)
060set ocidModifyString to (item 1 of listResponse)
061#改行をUNIXに
062set ocidModifyString to (ocidModifyString's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
063set ocidModifyString to (ocidModifyString's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
064#最後の改行を調べて
065set boolSuffixLF to (ocidModifyString's hasSuffix:("\n")) as boolean
066#最後の文字が改行なら削除しておく
067if boolSuffixLF is true then
068  #文字数のレンジ
069  set ocidLegth to ocidModifyString's |length|()
070  set ocidModifyString to ocidModifyString's substringToIndex:(ocidLegth - 1)
071end if
072
073############################
074#削除テキストをリスト化
075set ocidModifyArray to ocidModifyString's componentsSeparatedByString:("\n")
076set numCntModifyArray to ocidModifyArray's |count|()
077#総数カウント用
078set numCntMachAll to 0 as integer
079#リストを順に処理
080repeat with itemArray in ocidModifyArray
081  log "対象語句: " & itemArray as text
082  #正規表現にして
083  set strSetPattern to ("^" & itemArray & "\\s*$\\n?") as text
084  set ocidOption to (refMe's NSRegularExpressionAnchorsMatchLines)
085  set listResponse to (refMe's NSRegularExpression's regularExpressionWithPattern:(strSetPattern) options:(ocidOption) |error| :(reference))
086  set appRegex to (item 1 of listResponse)
087  #文字数のレンジ
088  set ocidLegth to ocidSummaryString's |length|()
089  #範囲のレンジ
090  set ocidRange to refMe's NSRange's NSMakeRange(0, ocidLegth)
091  #マッチした件数を数えておく
092  set ocidMatchArray to (appRegex's matchesInString:(ocidSummaryString) options:0 range:(ocidRange))
093  set numCntMachAll to numCntMachAll + (ocidMatchArray's |count|())
094  log "マッチ件数:" & ocidMatchArray's |count|()
095  #正規表現実行
096  set ocidResultText to (appRegex's stringByReplacingMatchesInString:(ocidSummaryString) options:0 range:(ocidRange) withTemplate:(""))
097  #次のキーワードに備える
098  set ocidSummaryString to ocidResultText
099end repeat
100
101############################
102#保存
103set ocidSaveArray to ocidSummaryString's componentsSeparatedByString:("\n")
104set numCntSaveArray to ocidSaveArray's |count|()
105#
106set listDone to ocidSummaryString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error| :(reference)
107if (item 1 of listDone) is true then
108  log "正常終了"
109  log "元データ件数:" & (numCntSummaryArray as integer) as text
110  log "削除データ件数:" & (numCntModifyArray as integer) as text
111  log "マッチ削除件数:" & numCntMachAll
112  log "保存件数: " & numCntSaveArray
113else if (item 1 of listDone) is false then
114  log (item 2 of listDone)'s localizedDescription() as text
115  return "保存に失敗しました"
116end if
AppleScriptで生成しました

|

[正規表現]バックリファレンス付きの置換


あくまでも参考にしてください

【スクリプトエディタで開く】 |

サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004#com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006use AppleScript version "2.8"
007use framework "Foundation"
008use framework "AppKit"
009use scripting additions
010
011
012property refMe : a reference to current application
013
014
015set strText to (" NSRTFTextDocumentType ") as text
016set ocidText to refMe's NSString's stringWithString:(strText)
017
018set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
019ocidTextM's setString:(ocidText)
020
021##正規表現パターン
022set strPattern to ("(\\bNS\\w*?\\b)") as text
023##
024set strTemplate to ("<b>$1</b>") as text
025
026set ocidStrRange to ocidTextM's rangeOfString:(ocidTextM)
027
028ocidTextM's replaceOccurrencesOfString:(strPattern) withString:(strTemplate) options:(refMe's NSRegularExpressionSearch) range:(ocidStrRange)
029
030log ocidTextM as text
031
AppleScriptで生成しました

|

【日英判定】Safari google翻訳


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

set appFileManager to refMe's NSFileManager's defaultManager()

########################
## クリップボードの中身取り出し
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "入力してください" as text
  end if
end if

###ダイアログ
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasIconPath to (POSIX file "/System/Library/CoreServices/Tips.app/Contents/Resources/AppIcon.icns") as alias
set strTitle to ("入力してください") as text
set strMes to ("【日英判定】翻訳します\rSafariで開きます\r") as text
set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)

if (gave up of recordResult) is true then
return "時間切れです"
else if (button returned of recordResult) is "キャンセル" then
return "キャンセルです"
else
  set strReturnedText to (text returned of recordResult) as text
end if
set ocidText to refMe's NSString's stringWithString:(strReturnedText)
###########################
###URL整形 URLコンポーネントを使う
set ocidURLComponents to refMe's NSURLComponents's alloc()'s init()
##スキームとホスト
ocidURLComponents's setScheme:("https")
ocidURLComponents's setHost:("translate.google.com")
##クエリーアイテムにセットするArray
set ocidQueryItemArray to refMe's NSMutableArray's alloc()'s initWithCapacity:0

###########################
###【日本語判定】大まかな日本語陵域
set ocidPattern to refMe's NSString's stringWithString:("[ぁ-んァ-ン一-鿿]+")
###正規表現を定義↑のパターンでセット
set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:(ocidPattern) options:(0) |error|:(reference)
##error referenceしているので戻り値はリストだから
set ocidRegex to (item 1 of listRegex)
###入力文字列のレンジ
set ocidImputRange to refMe's NSMakeRange(0, ocidText's |length|())
###文字列の中に正規表現が最初に当てはまるレンジは?
set ocidRange to ocidRegex's rangeOfFirstMatchInString:(ocidText) options:0 range:(ocidImputRange)
###レンジのロケーションを取り出して
set ocidLocation to ocidRange's location()
##NSNotFoundなら
if ocidLocation = refNSNotFound then
  log "日本語を含みません 日本語に翻訳します"
  ##元テキスト autoも可
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("sl") value:("en")
ocidQueryItemArray's addObject:(ocidQueryItem)
  ##翻訳後の言語
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("tl") value:("ja")
ocidQueryItemArray's addObject:(ocidQueryItem)
  ##ユーザーインターフェイスの言語 USで英語 JP で日本語
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("hl") value:("us")
ocidQueryItemArray's addObject:(ocidQueryItem)
  
else
  ###あるなら
  log "日本語を含みます 英語に翻訳します"
  ##元テキスト autoも可
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("sl") value:("ja")
ocidQueryItemArray's addObject:(ocidQueryItem)
  ##翻訳後の言語
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("tl") value:("en")
ocidQueryItemArray's addObject:(ocidQueryItem)
  ##ユーザーインターフェイスの言語 USで英語 JP で日本語
  set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("hl") value:("jp")
ocidQueryItemArray's addObject:(ocidQueryItem)
  
end if
###########################
###言語に影響ないクエリーの残り
set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("op") value:("translate")
ocidQueryItemArray's addObject:(ocidQueryItem)
set ocidQueryItem to refMe's NSURLQueryItem's alloc()'s initWithName:("text") value:(strReturnedText)
ocidQueryItemArray's addObject:(ocidQueryItem)
##全てのクエリーをセット
ocidURLComponents's setQueryItems:(ocidQueryItemArray)
###URLに
set ocidURL to ocidURLComponents's |URL|
set strGetURL to ocidURL's absoluteString() as text

#############
###Safari
###Safariで開く
tell application "Safari" to launch
tell application "Safari"
  activate
  ##ウィンドウの数を数えて
  set numCntWindow to (count of every window) as integer
  ###ウィンドウがなければ
  if numCntWindow = 0 then
    ###新規でウィンドウを作る
make new document with properties {name:strReturnedText}
    tell front window
      open location strGetURL
    end tell
  else
    ###ウィンドウがあるなら新規タブで開く
    tell front window
make new tab
      tell current tab
open location strGetURL
      end tell
    end tell
  end if
end tell

#################################
##クオテーションの置換用
to doReplace(argOrignalText, argSearchText, argReplaceText)
  set strDelim to AppleScript's text item delimiters
  set AppleScript's text item delimiters to argSearchText
  set listDelim to every text item of argOrignalText
  set AppleScript's text item delimiters to argReplaceText
  set strReturn to listDelim as text
  set AppleScript's text item delimiters to strDelim
return strReturn
end doReplace
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ##テキスト形式に確定
  set strTextToEncode to ocidArgTextEncoded as text
  ###値を戻す
return strTextToEncode
end doUrlEncode




|

【日英判定】Safari_mirai_translate 翻訳


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.6"
use framework "Foundation"
use framework "AppKit"
use framework "UniformTypeIdentifiers"
use scripting additions
property refMe : a reference to current application
property refNSNotFound : a reference to 9.22337203685477E+18 + 5807

set appFileManager to refMe's NSFileManager's defaultManager()

########################
## クリップボードの中身取り出し
###初期化
set appPasteboard to refMe's NSPasteboard's generalPasteboard()
set ocidPastBoardTypeArray to appPasteboard's types
###テキストがあれば
set boolContain to ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text"
if boolContain = true then
  ###値を格納する
  tell application "Finder"
    set strReadString to (the clipboard as text) as text
  end tell
  ###Finderでエラーしたら
else
  set boolContain to ocidPastBoardTypeArray's containsObject:"NSStringPboardType"
  if boolContain = true then
    set ocidReadString to ocidPasteboard's readObjectsForClasses:({refMe's NSString}) options:(missing value)
    set strReadString to ocidReadString as text
  else
    log "テキストなし"
    set strReadString to "入力してください" as text
  end if
end if

###ダイアログ
set strName to (name of current application) as text
if strName is "osascript" then
  tell application "Finder" to activate
else
  tell current application to activate
end if
set aliasIconPath to (POSIX file "/System/Library/CoreServices/Tips.app/Contents/Resources/AppIcon.icns") as alias
set strTitle to ("入力してください") as text
set strMes to ("【日英判定】翻訳します\rSafariで開きます\r") as text
set recordResult to (display dialog strMes with title strTitle default answer strReadString buttons {"キャンセル", "OK"} default button "OK" cancel button "キャンセル" giving up after 30 with icon aliasIconPath without hidden answer)

if (gave up of recordResult) is true then
return "時間切れです"
else if (button returned of recordResult) is "キャンセル" then
return "キャンセルです"
else
  set strReturnedText to (text returned of recordResult) as text
end if
set ocidText to refMe's NSString's stringWithString:(strReturnedText)
###NSURLを使わないのでクエリー用に%エンコードしておく
set strEncText to doUrlEncode(strReturnedText)
set ocidEncText to refMe's NSString's stringWithString:(strEncText)
###########################
###URL整形
set strURL to ("https://miraitranslate.com/trial/") as text
set ocidBaseURL to refMe's NSString's stringWithString:(strURL)
##
(*
auto 自動
ja 日本
en 英語
ko 韓国
zh 北京語
zt 台湾語
it イタリア
id インドネシア
uk ウクライナ
es スペイン
th タイ
de ドイツ
fr フランス
vi ベトナム
pt ポルトガル
ru ロシア
*)


###########################
###【日本語判定】大まかな日本語陵域
set ocidPattern to refMe's NSString's stringWithString:("[ぁ-んァ-ン一-鿿]+")
###正規表現を定義↑のパターンでセット
set listRegex to refMe's NSRegularExpression's regularExpressionWithPattern:(ocidPattern) options:(0) |error|:(reference)
##error referenceしているので戻り値はリストだから
set ocidRegex to (item 1 of listRegex)
###入力文字列のレンジ
set ocidImputRange to refMe's NSMakeRange(0, ocidText's |length|())
###文字列の中に正規表現が最初に当てはまるレンジは?
set ocidRange to ocidRegex's rangeOfFirstMatchInString:(ocidText) options:0 range:(ocidImputRange)
###レンジのロケーションを取り出して
set ocidLocation to ocidRange's location()
##NSNotFoundなら
if ocidLocation = refNSNotFound then
  log "日本語を含みません 日本語に翻訳します"
  ##
  set ocidEncBaseURL to ocidBaseURL's stringByAppendingPathComponent:("#en/ja/")
else
  ###あるなら
  set ocidEncBaseURL to ocidBaseURL's stringByAppendingPathComponent:("#ja/en/")
  
end if
###########################
###
set ocidGetURL to ocidEncBaseURL's stringByAppendingPathComponent:(ocidEncText)
set strGetURL to ocidGetURL as text

#############
###Safari
###Safariで開く
tell application "Safari" to launch
tell application "Safari"
  activate
  ##ウィンドウの数を数えて
  set numCntWindow to (count of every window) as integer
  ###ウィンドウがなければ
  if numCntWindow = 0 then
    ###新規でウィンドウを作る
make new document with properties {name:strReturnedText}
    tell front window
      open location strGetURL
    end tell
  else
    ###ウィンドウがあるなら新規タブで開く
    tell front window
make new tab
      tell current tab
open location strGetURL
      end tell
    end tell
  end if
end tell

#################################
##クオテーションの置換用
to doReplace(argOrignalText, argSearchText, argReplaceText)
  set strDelim to AppleScript's text item delimiters
  set AppleScript's text item delimiters to argSearchText
  set listDelim to every text item of argOrignalText
  set AppleScript's text item delimiters to argReplaceText
  set strReturn to listDelim as text
  set AppleScript's text item delimiters to strDelim
return strReturn
end doReplace
####################################
###### %エンコード
####################################
on doUrlEncode(argText)
  ##テキスト
  set ocidArgText to refMe's NSString's stringWithString:(argText)
  ##キャラクタセットを指定
  set ocidChrSet to refMe's NSCharacterSet's URLQueryAllowedCharacterSet
  ##キャラクタセットで変換
  set ocidArgTextEncoded to ocidArgText's stringByAddingPercentEncodingWithAllowedCharacters:(ocidChrSet)
  ##テキスト形式に確定
  set strTextToEncode to ocidArgTextEncoded as text
  ###値を戻す
return strTextToEncode
end doUrlEncode




|

[Jedit Ω]正規表現でNULL文字除去


【スクリプトエディタで開く】|

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




tell application "Jedit Ω"
  set strSerchText to "\\x{00}"
  tell front document
replaceAll string "\\x{00}" to "" with grep, select all, case sensitive, character width sensitive and diacritic sensitive
  end tell
end tell

AppleScriptでやるとおおげさな感じになるなぁ

【スクリプトエディタで開く】|

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


tell application "Jedit Ω"
  tell front document
    set strEveryText to every text
  end tell
end tell


set ocidEveryText to refMe's NSString's stringWithString:(strEveryText)
set ocidTextM to refMe's NSMutableString's alloc()'s initWithCapacity:(0)
ocidTextM's appendString:(ocidEveryText)


#################################################
## 正規表現でNULL文字削除
#################################################

set ocidRegOption to (refMe's NSRegularExpressionUseUnicodeWordBoundaries)
(*
-->(*1*)アルファベットの大文字と小文字の区別無し
(refMe's NSRegularExpressionCaseInsensitive)
-->(*2*)スペースと#コメントを無視
(refMe's NSRegularExpressionAllowCommentsAndWhitespace)
-->(*4*)メタ文字無視
(refMe's NSRegularExpressionIgnoreMetacharacters)
-->(*8*)ドット=.が改行コードにもマッチ
(refMe's NSRegularExpressionDotMatchesLineSeparators)
-->(*16*)行頭行末の^$が各行マッチ
(refMe's NSRegularExpressionAnchorsMatchLines)
-->(*32*)\nだけが改行コード 他の改行コードはマッチの対象
(refMe's NSRegularExpressionUseUnixLineSeparators)
-->(*64*)ユニコード式の文字区切り \b
(refMe's NSRegularExpressionUseUnicodeWordBoundaries)
*)
set listRegularExpression to refMe's NSRegularExpression's regularExpressionWithPattern:("\\x00") options:(ocidRegOption) |error|:(reference)
set ocidRegex to (item 1 of listRegularExpression)
set ocidLength to ocidTextM's |length|()
set ocidTextRange to refMe's NSMakeRange(0, ocidLength)
set ocidMachOption to (refMe's NSMatchingReportProgress)
(*
-->(*1*) ブロックを定期的に呼び出
(refMe's NSMatchingReportProgress)
-->(*2*)マッチングが完了したら、ブロックを 1 回呼び出し
(refMe's NSMatchingReportCompletion)
-->(*4*)一致を検索範囲の先頭の一致に限定
(refMe's NSMatchingAnchored)
-->(*8*)検索範囲の境界を越える文字列の一部を照合
(refMe's NSMatchingWithTransparentBounds)
-->(*16*)文字列全体の先頭と末尾には一致
(refMe's NSMatchingWithoutAnchoringBounds)
*)
set ocidResults to ocidRegex's stringByReplacingMatchesInString:(ocidTextM) options:(ocidMachOption) range:(ocidTextRange) withTemplate:("")
set strTrimText to ocidResults as text

tell application "Jedit Ω"
  tell front document
    set every text to strTrimText
  end tell
end tell

|

NSMatchingOptions


【スクリプトエディタで開く】|

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


-->(*1*) ブロックを定期的に呼び出
log (refMe's NSMatchingReportProgress) as integer
-->(*2*)マッチングが完了したら、ブロックを 1 回呼び出し
log (refMe's NSMatchingReportCompletion) as integer
-->(*4*)一致を検索範囲の先頭の一致に限定
log (refMe's NSMatchingAnchored) as integer
-->(*8*)検索範囲の境界を越える文字列の一部を照合
log (refMe's NSMatchingWithTransparentBounds) as integer
-->(*16*)文字列全体の先頭と末尾には一致
log (refMe's NSMatchingWithoutAnchoringBounds) as integer

|

[NSRegularExpressionSearch]行末に<br>(BLOG投稿用)


【スクリプトエディタで開く】|

#!/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 framework "AppKit"
use scripting additions

property refMe : a reference to current application

##########################################
###ペーストボード
##########################################
####ペーストボード宣言
set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
####中に格納されているデータタイプを取得
set ocidPastBoardTypeArray to ocidPasteboard's types
log ocidPastBoardTypeArray as list
if (ocidPastBoardTypeArray's containsObject:"public.utf8-plain-text") is true then
  set ocidPublicText to ocidPasteboard's stringForType:(refMe's NSPasteboardTypeString)
else
return "テキストを取得出来ません"
end if
##########################################
###置換
##########################################
###可変テキスト確定
set ocidOutPutString to refMe's NSMutableString's alloc()'s initWithCapacity:0
ocidOutPutString's setString:(ocidPublicText)

###テキスト全体のレンジを取得して
set ocidNSRange to ocidOutPutString's rangeOfString:(ocidOutPutString)
###置換
ocidOutPutString's replaceOccurrencesOfString:("$") withString:("\n") options:(refMe's NSRegularExpressionSearch) range:ocidNSRange
###テキスト全体のレンジを取得して
set ocidNSRange to ocidOutPutString's rangeOfString:(ocidOutPutString)
###置換
ocidOutPutString's replaceOccurrencesOfString:("\n") withString:("<br/>\n") options:(refMe's NSRegularExpressionSearch) range:ocidNSRange


##########################################
###ペーストボードに戻す
##########################################
ocidPasteboard's clearContents()
ocidPasteboard's setString:(ocidOutPutString) forType:(refMe's NSPasteboardTypeString)


|

[文字列置換]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*)

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Admin XProtect Adobe Adobe Bridge Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time defaults delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData ffmpeg File File Name Finder Firefox Folder FolderAction Fonts Fonts ATS Fonts Python Foxit GIF github Guide HTML Icon Illustrator Image Events Image2PDF ImageOptim Input Dictionary iPhone iWork Javascript Jedit Json Label Language Leading Zero List locationd LRC lsappinfo m3u8 Mail MakePDF 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 Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDF Pymupdf PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC 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 webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube zoom