Tbpgr Blog

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

書籍 Regular Expressions Cookbook | Replace All Matches Within the Matches of Another Regex

パンくず

書籍 Regular Expressions Cookbook
Replace All Matches Within the Matches of Another Regex

概要

正規表現で抽出した内容のうち、
更に別の正規表現に一致するもののみ置換する

サンプル

# タグの中の文字列がbeforeだった場合のみ置換する
subject = "<b>before</b>"
innerre = /before/
result = subject.gsub(/<b>.*?<\/b>/) {|match|
    match.gsub(innerre, 'after')
}
pp result #=>"<b>after</b>"