Home > XModules >

必要なシステム

  • OS X 10.9 以降
    • macOS 10.14.6 で開発及びテストをしています。

ダウンロード

Version 1.0.1 -- 2021-04-09

依存モジュール

XRegex

正規表現による文字列処理の AppleScript ライブラリです。正規表現にパターンマッチング、マッチした文字列の抽出、置換が行えます。内部で NSRegularExpression を使用しています。

簡単には、クラスメソッドの search, serarch_all, replace_matches を使うと良いでしょう。

seach は最初にマッチした MatchResult を返します。MatchResult は、正規表現にマッチしたテキストと場所に関する情報を保持したオブジェクトです。MatchResult の capture でマッチしたテキスト、range でマッチした位置及び範囲を得ることができます。

NSString と AppleScript テキストでは、文字列の長さの勘定が一致しないことがあります。range で取得した場所及び長さから部分文字列を取得する際は、MatchResult オブジェクトの substring, substring_from を使ってください。

search_all は、検索対象としたテキストの全てを走査してマッチした全ての MatchResult をリストで返します。

replace_machtes は、マッチしたテキストを置き換えます。置換文字で正規表現中のグループの後方参照が使えますので、高度で複雑な置換処理を行えます。

同じ正規表現を繰り返し使う場合は、make_with で XRegex インスタンスを生成すると良いでしょう。インスタンスを生成することによって、なんども正規表現をコンパイルするオーバーヘッドを避けることができます。インスタンスに対しては、first_match, matches_in, replace を使って、上記の同じことができます。

use XRegex : script "XRegex"

(*** Using Class methods ***)
-- Obtain first matche
tell XRegex's search("\\d{4}", "1972-01-27")
if it is not missing value then
log capture(0) (*1972*)
log range(0) (*length:4, location:0*)
end if
end tell

-- Obtain all mathes
tell XRegex's search_all("\\d{2}", "1972-01-27")
repeat with a_match in it
tell a_match
log capture(0)
log range(0)
(*19*)
(*length:2, location:0*)
(*72*)
(*length:2, location:2*)
(*01*)
(*length:2, location:5*)
(*27*)
(*length:2, location:8*)
end tell
end repeat
end tell

-- Replace
log XRegex's replace_matches("\\d{2}", "1972-01-27", "xx") (*xxxx-xx-xx*)

(*** Compiling Regular Expression and Working with Instance Methods ***)
-- Simple cases
tell XRegex's make_with("(\\d{4})-\\d{1,2}-\\d{1,2}")
log count_in("2020-10-10") (*1*)

tell first_match("2020-10-10")
if it is not missing value then
log (count it) (*2*)
log its capture(0) -- 2020-10-10 : whole match
log its capture(1) -- 2020 : first capture
end if
end tell
end tell

-- Obtain matched all sub-texts
tell XRegex's make_with("\\d{2}")
set matches to matches_in("2021-10-20")
end tell
log (count matches) (*4*)
tell item 1 of matches
log (count it) (*1*)
log capture(0) (*20*)
log range(0) (*length:2, location:0*)
end tell

tell item 2 of matches
log (count it) (*1*)
log capture(0) (*21*)
set {location:loc, length:len} to range(0) (*length:2, location:2*)
--obtain substring
log substring(loc + 3, len) (*10*)
end tell


-- Replace
tell XRegex's make_with("http://([^/]+)(/[^/]+)*")
log replace("http://www.script-factory.net/index.html", ¬
"https://$1")
(*https://www.script-factory.net*)
end tell

-- split
tell XRegex's make_with("\\s*,\\s*")
log split("a , b,c")
(*a, b, c*)
end tell

return true

更新履歴

  • 1.0.1 -- 2021-04-09
    • split を追加
  • 1.0 -- 2020-06-26
    • 初公開