Groovyで文字列を単語に分ける

したいこと

  • 1.空白類文字を区切りにして分ける
  • 2.「(」や「,」などの記号なども区切りにして分ける

ソース

Groovy_in_Action_english ="[Papaerback] [Dierk Koenig (Author), Andrew Glover (Author), Paul King (Author), Guillaume Laforge (Author), Jon Skeet (Author), James Gosling (Foreword)] Groovy, the brand-new language for the Java platform, brings to Java many of the features that have made Ruby popular."


println "1.空白類文字を区切りにして分ける"
Groovy_in_Action_english.split().each{ word ->
        println word
}


println "2. 記号なども区切りにして分ける"
println "2-1. 単語構成文字:[a-zA-Z_0-9]だけで成り立っているものを単語とみなす"
println "2-1-1. matcherを使う"
(Groovy_in_Action_english =~/\w+/).each{ word ->
        println word
}

println "2-1-1. splitを使う (指定するのは区切り文字だから正規表現が逆転する)"
Groovy_in_Action_english.split(/\W+/).each{ word ->
        println word
}


println "2-2. 単語構成文字だけ、または、記号(非空白文字と非単語構成文字の組み合わせ)で成り立っている2つを単語とみなす"
(Groovy_in_Action_english =~/\w+|[^\s\w]+/).each{ word ->
        println word
}

結果

[D:\workspace\groovy_SandBox]groovy Q047_文字列を単語に分ける.groovy
1.空白類文字を区切りにして分ける
[Papaerback]
[Dierk
Koenig
(Author),
Andrew
Glover
(Author),
Paul
King
(Author),
Guillaume
Laforge
(Author),
Jon
Skeet
(Author),
James
Gosling
(Foreword)]
Groovy,
the
brand-new
language
for
the
Java
platform,
brings
to
Java
many
of
the
features
that
have
made
Ruby
popular.
2. 記号なども区切りにして分ける
2-1. 単語構成文字:[a-zA-Z_0-9]だけで成り立っているものを単語とみなす
2-1-1. matcherを使う
Papaerback
Dierk
Koenig
Author
Andrew
Glover
Author
Paul
King
Author
Guillaume
Laforge
Author
Jon
Skeet
Author
James
Gosling
Foreword
Groovy
the
brand
new
language
for
the
Java
platform
brings
to
Java
many
of
the
features
that
have
made
Ruby
popular
2-1-1. splitを使う (指定するのは区切り文字だから正規表現が逆転する)

Papaerback
Dierk
Koenig
Author
Andrew
Glover
Author
Paul
King
Author
Guillaume
Laforge
Author
Jon
Skeet
Author
James
Gosling
Foreword
Groovy
the
brand
new
language
for
the
Java
platform
brings
to
Java
many
of
the
features
that
have
made
Ruby
popular
2-2. 単語構成文字だけ、または、記号(非空白文字と非単語構成文字の組み合わせ)で成り立っている2つを単語とみなす
[
Papaerback
]
[
Dierk
Koenig
(
Author
),
Andrew
Glover
(
Author
),
Paul
King
(
Author
),
Guillaume
Laforge
(
Author
),
Jon
Skeet
(
Author
),
James
Gosling
(
Foreword
)]
Groovy
,
the
brand
-
new
language
for
the
Java
platform
,
brings
to
Java
many
of
the
features
that
have
made
Ruby
popular
.

splitを使うと、指定するのは区切り文字だから条件が多いと正規表現が逆転するのでややこしい。
空白で区切るときだけにした方がよさそうだ。




実行環境




関連あるかもしれない記事












Groovyの詳細についてはJavadocと以下の書籍を参考にしている。

Groovyイン・アクション
Dierk Konig Andrew Glover Paul King Guillaume Laforge Jon Skeet
毎日コミュニケーションズ
売り上げランキング: 294340


問題自体は以下の書籍のもの。rubyと似てる部分も多いので、ヒントにもなる。
写経でもいいが自分で考えるために他言語の例をGroovyで置き換えてる。

Rubyレシピブック 第2版 268の技
青木 峰郎 後藤 裕蔵 高橋 征義
ソフトバンク クリエイティブ
売り上げランキング: 80467


Groovyイン・アクションを読むならあった方が便利かな。

ブックストッパー

トモエ算盤
売り上げランキング: 614


Rubyレシピブックは「ほんたった」で立ててる