我的 MySQL 列中有一个包含 HTML 的文本 blob 字段。我必须更改一些标记,所以我想我会在 ruby 脚本中完成它。 Ruby 在这里无关紧要,但很高兴看到它的答案。标记如下所示:
<h5>foo</h5>
<table>
<tbody>
</tbody>
</table>
<h5>bar</h5>
<table>
<tbody>
</tbody>
</table>
<h5>meow</h5>
<table>
<tbody>
</tbody>
</table>
我只需要改变第一个<h5>foo</h5>
每个文本块<h2>something_else</h2>
同时留下绳子的其余部分。
使用 Ruby 似乎无法获得正确的 PCRE 正则表达式。
# 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
代替String#gsub
仅导致第一次替换发生。如果您需要动态选择“foo”是什么,可以在正则表达式文字中使用字符串插值:
new_str = my_str.sub( %r{<h5>#{searchstr}</h5>}, "<h2>#{replacestr}</h2>" )
话又说回来,如果您知道“foo”是什么,则不需要正则表达式:
new_str = my_str.sub( "<h5>searchstr</h5>", "<h2>#{replacestr}</h2>" )
or even:
my_str[ "<h5>searchstr</h5>" ] = "<h2>#{replacestr}</h2>"
如果需要运行代码来找出替换,可以使用 sub 的块形式:
new_str = my_str.sub %r{<h5>([^<]+)</h5>} do |full_match|
# The expression returned from this block will be used as the replacement string
# $1 will be the matched content between the h5 tags.
"<h2>#{replacestr}</h2>"
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)