LoginSignup
7
9

More than 3 years have passed since last update.

正規表現学習のためのegrep

Last updated at Posted at 2019-02-07

grepとは

grepは,global regular expression print の略で,文書ファイル中から正規表現を用いて何らかの文やワードを探すためのコマンドです.これに機能拡張したものがegrepです.
本ページは,J.E.F.Friedl著「詳説 正規表現 第2版」オライリージャパン
を参考にしました.

サンプルファイル

まず,検索対象のファイルを用意します.

grep_test.txt
apple
abstract
breath
tooth
index
indoor
construction
convolution
03/12/12
03.12.12
03-12-12
From:aaa
Date:1/1
this is an apple.
color
colour
colouur

基本的な使い方

egrep '検索内容' 検索対象 として使います.
また,大文字・小文字を無視する場合は,
egrep -i '検索内容' 検索対象
として,オプションをつけます.

$ egrep 'a' grep_test.txt
apple
abstract
breath
From:aaa
Date:1/1
this is an apple.

$ egrep -i 'd' grep_test.txt
index
indoor
Date:1/1

正規表現の導入

正規表現(regular expression, regex)は,メタ文字リテラルから成ります.
メタ文字は,チート記号みたいなものです(適当).その使い方を書いていきます.

文頭や文末・文中の単語に注目する

メタ文字 用途 意味
^ 文頭が一致するかどうか ^in inではじまる文
$ 文末が一致するかどうか th$ thでおわる文
< 単語の語頭 <i iではじまる語がある文
> 単語の語末 is> isでおわる語がある文
$ egrep '^in' grep_test.txt
index
indoor

$ egrep 'th$' grep_test.txt
breath
tooth

$ egrep '\<i' grep_test.txt
index
indoor
this is an apple.

$ egrep 'is\>' grep_test.txt
this is an apple.

連続した文字

メタ文字 用途
? メタ文字の前のリテラルが0個または1個 colou?r
* メタ文字の前のリテラルが0個以上 colou*r
+ メタ文字の前のリテラルが1個以上 colou+r
{min,max} メタ文字の前のリテラルの数制限 colou{1,2}r
$ egrep 'colou?r' grep_test.txt
color
colour

$ egrep 'colou*r' grep_test.txt
color
colour
colouur

$ egrep 'colou+r' grep_test.txt
colour
colouur

$ egrep 'colou{1,2}r' grep_test.txt
colour
colouur

複数の単語候補から探す

メタ文字 用途
. 任意の文字 03.12.12
[ ] [ ]内の文字のどれか br[ea]ath / br[a-f]ath
[^ ] [ ]内でない文字のどれか ^con[^v]
\ 後ろのメタ文字をエスケープする \$

-はその範囲の文字のどれかを表す.a-fはアルファベットのaからfのどれか.

$ egrep '03.12.12' grep_test.txt
03/12/12
03.12.12
03-12-12

$ egrep 'br[ea]ath' grep_test.txt
breath // breath かbraathを探す

$ egrep '^con[^v]' grep_test.txt
construction //convolutionは除外されてconstructionのみ

$ egrep '[0-9]*.12.12' grep_test.txt
03/12/12
03.12.12
03-12-12
7
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9