第8章 その他の Java 8 機能を理解する : 問題 15 : 簡易 grep
問題
Files.lines
とPattern#asPredicate
を使用して、与えられた正規表現に一致するすべての行を表示する grep のようなプログラムを書け。
解答
機能をいろいろ盛り込みたいところだけど、ここは簡潔に以下のような仕様とする。
- 第1引数は正規表現の式、第2引数はファイルのパス
CASE_INSENSITIVE
などのオプションは用意しない
埋め込みフラグ表現(?i
)を使うこと- ファイルのパスにディレクトリは指定できない
- ファイルのパスにワイルドカードは使えない
- 単にマッチした行を標準出力に出力するだけ
■ main メソッド
public static void main(String[] args) { // コマンドライン引数のチェック if (args.length < 2) { System.out.println("Usage : grep <regular expression> <file path>"); return; } // コマンドライン引数から正規表現とファイルのパスを取得 Pattern pattern = Pattern.compile(args[0]); Path path = Paths.get(args[1]); // 検索 try (Stream<String> stream = Files.lines(path)) { stream.filter(pattern.asPredicate()) .forEach(System.out::println); } catch (IOException ex) { ex.printStackTrace(); } }
実質、3ステップで出来ちゃうんですね。
不思議の国のアリスから "Wonderland" を検索してみると…
■ 実行結果
> grep (?i)wonderland alice.txt Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll Title: Alice's Adventures in Wonderland *** START OF THIS PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND *** ALICE'S ADVENTURES IN WONDERLAND Wonderland, though she knew she had but to open them again, and all with the dream of Wonderland of long ago: and how she would feel with End of Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll *** END OF THIS PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***