Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.
  • 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のリストに変更
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away