0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ruby 正規表現 複数パターン[備忘録]

Posted at

rubyの正規表現における複数パターン

こんにちは!最近rubyの正規表現における複数パターンについて調べる機会があったので備忘録として残しておきます。

string = 'ruby'
string =~ (/python|ruby/)

| バーティカルバー(読み方初めて知りました笑)でマッチさせたい文字列を区切ります。
もしマッチすればマッチした文字列の位置の数字を返してくれます。上の例で言えば0が返ってきます。

string = 'fruby'
string =~ (/python|ruby/)

少しわかりずらいのでもう1つ例を出します。上の例で言えば1が返ってきます。
string = 'fruby' この文字列の中でrubyは1番目から始まるので1が返り値として返ってきます。

a = 'python
if a =~ (/ruby|python/)
    puts 'good'
end

=~は正規表現に使える演算子です。上のコードはマッチすれば'good'を出力するというプログラムです。
逆にマッチしなかった時に何かをしたい場合は

a = 'java'
if a !~ (/ruby|python/)
    puts 'bad'
end

!~と書いてあげることでマッチしなかった時の処理を記述できます。上のプログラムはbadを出力します。

rubyの正規表現における複数パターンの書き方と演算子について説明しました。よかったら参考にしてください。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?