# The regex literal syntax using %r{...} allows / in your regex without escaping new_str = my_str.sub( %r{<h5>[^<]+</h5>}, '<h2>something_else</h2>' )
Using String#sub instead of String#gsub only causes the first replacement. If you need to dynamically select what "foo" is, you can use string interpolation in regular expression literals:
new_str = my_str.sub( %r{<h5>#{searchstr}</h5>}, "<h2>#{replacestr}</h2>" )
Then, if you know what "foo" is, you do not need a regular expression:
new_str = my_str.sub( "<h5>searchstr</h5>", "<h2>#{replacestr}</h2>" )
or even:
my_str[ "<h5>searchstr</h5>" ] = "<h2>#{replacestr}</h2>"
If you need to run the code to determine the replacement, you can use the sub block form:
new_str = my_str.sub %r{<h5>([^<]+)</h5>} do |full_match|
Phrogz
source share