Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

書籍 Regular Expressions Cookbook | Capture and Name Parts of the Match

パンくず

書籍 Regular Expressions Cookbook
Capture and Name Parts of the Match

概要

名前付きキャプチャについて

構文

(?<name>regexp) # => 名前付き後方参照宣言
\k<name># => 名前付き後方参照利用

サンプル

後方参照にyear,month,dayという名前を付けて利用

target = "昭和30年02月22日"
reg = /昭和(?<year>\d{2})(?<month>\d{2})(?<day>\d{2})/
replace = 'S\k<year>/\k<month>/\k<day>'
puts target.gsub(reg,replace) # => 置換結果:S30/02/22