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を使うと、指定するのは区切り文字だから条件が多いと正規表現が逆転するのでややこしい。
空白で区切るときだけにした方がよさそうだ。
実行環境
- OS:Windows XP
- Groovy Version: 1.6.5
- JVM: 1.6.0_12
Groovyでoutputzの文字数を取得する(改行の改造版)
groovyでoutputzの文字数を取得する
GroovyでRijndael(Rijn.dll)を使用した暗号化・復号化
Groovyでカンマで区切られたデータ(CSV)を処理する
Groovyで文字列を単語に分ける.groovy
Groovyでファイルを行単位で処理する
Groovyでファイルを開く
Groovyでグラフを作成する 4)日付表示を“日-月”から“月/日”に変更する 設定方法のバリエーション編
Groovyの詳細についてはJavadocと以下の書籍を参考にしている。
Groovyイン・アクション
posted with amazlet
問題自体は以下の書籍のもの。rubyと似てる部分も多いので、ヒントにもなる。
写経でもいいが自分で考えるために他言語の例をGroovyで置き換えてる。
Rubyレシピブック 第2版 268の技
posted with amazlet
Groovyイン・アクションを読むならあった方が便利かな。