これって学校の宿題でつか?


どうも、sepsplit() という関数を作って欲しいのですが、どこかの学校の宿題丸投げのような記法に笑ってしまいました。(ひょっとしたら真面目な問題なのかもしれませんが)

Question

その宿題 (?) とは、

function sepsplit(re, a, s) in POSIX awk with:
s is split into the fields a[0], a[2], ...,a[2n] by the field separator
regex re and a[2*i+1] is the string matched by re between a[2*i] and
a[2*i+2] for i = 0, 1, ..., n - 1. sepsplit() returns n.

つまり、

POSIX awk で関数 sepsplit(re, a, s) を作れ:
s は正規表現 re でフィールド分割された a[0], a[2], ...,a[2n] であり、
a[2*i+1] は re にマッチした文字列であり、a[2*i] と a[2*i+2] の間では
n を返す。

Answer

William James が「以前作ったことがあるよ」とサクッと答えているのですが、これって有名な問題なのでしょうか?

# Produces array of nonmatching and matching
# substrings. The size of the array will
# always be an odd number. The first and the
# last item will always be nonmatching.
function shatter( s, shards, regexp )
{ gsub( regexp, "\1&\1", s  )
  return split( s, shards, "\1" )
}