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 1 year has passed since last update.

【正規表現】subとgsub

Last updated at Posted at 2022-11-17

sub

「substitute:代用する、代わりに使う」の「sub」
「変数.sub(/代用前/,"代用後")」の形で使う。

irb(main):001:0> str = "おにぎりを食べる"
=> "おにぎりを食べる"

irb(main):002:0> str.sub(/おにぎり/,"ラーメン")
=> "ラーメンを食べる"

ただ、最初の一つしか入れ替わらない。

irb(main):001:0> str = "チャーシューおにぎりとツナマヨおにぎりを食べる"
=> "チャーシューおにぎりとツナマヨおにぎりを食べる"

irb(main):002:0> str.sub(/おにぎり/,"ラーメン")
=> "チャーシューラーメンとツナマヨおにぎりを食べる"

gsub

「g」は「グローバルマッチ」の「g」
複数含まれていても入れ代わる。

irb(main):001:0> str = "チャーシューおにぎりとツナマヨおにぎりを食べる"
=> "チャーシューおにぎりとツナマヨおにぎりを食べる"

irb(main):002:0> str.gsub(/おにぎり/,"ラーメン")
=> "チャーシューラーメンとツナマヨラーメンを食べる"

#techcamp136期

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?