LoginSignup
23
20

More than 1 year has passed since last update.

Ruby | 正規表現 | 末尾にマッチする「$」と「\Z」と「\z」の違い

Last updated at Posted at 2016-02-08

テキスト

たとえば次の通り、複数行のテキストがあるとする。
( 2行目の最後にも改行がある状態だ )

I am drinking
Everyday so much

ここでは確認用に、変数に収めておこう。

texts = "I am drinking" + "\n" + "Everyday so much" + "\n"

$ でのマッチ

$ はテキストを1行ずつ見ていく。そして1行ずつ判定する。

なので1行目単独でもマッチするし。

texts.match(/drinking$/) # => <MatchData "drinking">

2行目単独でもマッチする。

texts.match(/much$/) # => <MatchData "much">

\Z でのマッチ

\Z はテキスト全体を見る。

1行目は「テキスト全体の末尾」ではないので、以下はマッチしない。

texts.match(/drinking\Z/) # => nil

2行目は「テキスト全体の末尾」なので、以下はマッチする。

texts.match(/much\Z/) # => #<MatchData "much">

\z でのマッチ

\z もテキスト全体を見る。最も厳密なパターン。

\Z と違うのは「テキスト最後の改行」の扱いだ。

もちろん1行目にはマッチしない。

texts.match(/drinking\z/) # => nil 

2行目にもマッチしない。
なぜならテキストの最後に改行が入っているからだ。

texts.match(/much\z/) # => nil

正規表現で「末尾の改行」を明示すればマッチする。
この場合は「マッチの結果」に改行コードも含まれるようになる。

texts.match(/much\n\z/) # => <MatchData "much\n">

確認用スクリプト

texts = "I am drinking" + "\n" + "Everyday so much" + "\n"

p texts.match(/drinking$/) # => #<MatchData "drinking">
p texts.match(/much$/) # => #<MatchData "much">

puts

p texts.match(/drinking\Z/) # => nil
p texts.match(/much\Z/) # => #<MatchData "much">

puts

p texts.match(/drinking\z/) # => nil 
p texts.match(/much\z/) # => nil
p texts.match(/much\n\z/) # => <MatchData "much\n">

環境

  • ruby 2.3.0

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

23
20
0

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
23
20