LoginSignup
1
1

More than 5 years have passed since last update.

正規表現で置換する際に、あるパターンにマッチさせたいが、その一部のみを置換したい

Posted at

表題の際には以下の正規表現パターンを使えばいいと気づいた。
http://ref.xaio.jp/ruby/classes/string/gsub

Ruby 1.9では、パターンの中で(?<名前>パターン)という形でカッコに名前を付けられます。
第2引数replacementの中では、\k<名前>という書式でそのカッコに当てはまる部分を埋め込めます。

s = "one two, three four, five six"
puts s.gsub(/(?<first>\w+)\s+(?<second>\w+)/, '\k<second> \k<first>')
two one, four three, six five
1
1
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
1
1