LoginSignup
6
6

More than 5 years have passed since last update.

Cocoaの機能を使って正規表現で文字列を抽出するAppleScriptハンドラ

Last updated at Posted at 2016-01-15
  • do shell scriptを使わないとできなかった正規表現の文字列抽出
  • AppleScript上でCocoaの機能を使えるようになった
  • regexMatchesハンドラの返り値
    • マッチ箇所のリストで構成
    • マッチ自体もリストになっている
      • 1番目はマッチ全体の文字列
      • 2番目以降はキャプチャによる部分文字列
regexMatches.scpt
use scripting additions
use framework "Foundation"

my regexMatches("<p>あいうえお</p>", "<(.+?)>")
--> {{"<p>", "p"}, {"</p>", "/p"}}

on regexMatches(aText as text, pattern as text)
    --require framework: Foundation
    set regularExpression to current application's NSRegularExpression's regularExpressionWithPattern:pattern options:0 |error|:(missing value)
    set aString to current application's NSString's stringWithString:aText
    set matches to regularExpression's matchesInString:aString options:0 range:{location:0, |length|:aString's |length|()}

    set matchResultList to {}
    repeat with match in matches
        set matchResult to {}
        repeat with i from 0 to (match's numberOfRanges as integer) - 1
            set end of matchResult to (aString's substringWithRange:(match's rangeAtIndex:i)) as text
        end repeat
        set end of matchResultList to matchResult
    end repeat
    return matchResultList
end regexMatches

更新履歴

  • 2016-01-13: Cocoaの機能を使って作成
  • 2016-01-15: 返り値にキャプチャの結果を含めるように変更
  • 2016-01-20: NSMutableArrayの作成メソッドをnew:からarrayWithCapacity:に変更
  • 2016-02-16: matchResultListの作成をNSMutableArrayからAppleScriptのリストに変更
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6