Tbpgr Blog

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

書籍 Regular Expressions Cookbook | Insert the Regex Match into the Replacement Text

パンくず

書籍 Regular Expressions Cookbook
Insert the Regex Match into the Replacement Text

概要

マッチングした内容を後方参照で置換文字列内に埋め込む方法について

構文

マッチ内容をグループのindexを指定して取得

string.gsub(/(pattern1)(pattern2)(pattern3/, '\1\2\3')

サンプル

# マッチした箇所をindex指定で取得
puts "one two three".gsub(/(one) (two) (three)/,'\1-\2-\3') #=>置換後:one-two-three