Gaucheで文字列操作その2

昨日の続き.

正規表現で

(rxmatch #/test/ "hellotestworld")

というのがあるけど,よく使うので

(#/t\w*t/ "hellotestworld")

という略記法があるらしい.

で,このrxmatchはregmatchオブジェクトを返すが,それをそのまま実行すると,マッチ部分の文字列を得られる.

(define m (#/t\w*t/ "hellotestworld"))
(m)    ;  "test"

さらに,引数で’beforeや’afterを渡すと,そのマッチした文字列より前,後ろの文字列が得られる.

(m 'before)    ;  "hello"
(m 'after)     ;  "world"

複数マッチした場合は,引数にインデックスを渡してやると,対応する番号のマッチした文字列が返される.

(define m2 (#/(t\w*?t).(t\w*?t)*/ "hellotestworld hellothatworld")
(m2 0)     ; "testworld hellothat" (マッチした全体)
(m2 1)     ; "test"(1番目の括弧にマッチしたもの)
(m2 2)     ; "that"(2番目の括弧にマッチしたもの)

これらにも’beforeや’afterが付けられる

(m2 'before 0)   ; "hello"
(m2 'after  1)   ; "world hellothatworld"
(m2 'before 2)   ; "hellotestworld hello"

ふむふむ.

コメントする