简体   繁体   English

Ruby-删除h3标签替换为章节编号序列

[英]Ruby- delete h3 tags replace with sequence of chapter numbers

Ruby - Hi, I have max 200 html h3 headings in a html document. Ruby - 嗨,我在 html 文档中最多有 200 个 html h3 标题。 I am deleteing all, with characters between the two tags, using x.gsub(/\<h3\>(.*)\<\/h3\>/, '<h3>Chapter </h3>') .我正在使用x.gsub(/\<h3\>(.*)\<\/h3\>/, '<h3>Chapter </h3>')删除所有两个标签之间的字符。 My problem is: I need to insert the individual chapter numbers 1, 2, 3 and so on.我的问题是:我需要插入单独的章节编号 1、2、3 等等。 Is this possible using a hash or some other way?这可以使用 hash 或其他方式吗?

You could do this...你可以这样做...

# Establish a counter
i = 0
x.gsub( %r{<h3>(.+?)</h3>}i ){ |match| i+=1; "Chapter #{i}" }

The %r{...} is another way of defining a RegExp literal ( /.../ ), it helps here, so you don't need to escape the slash; %r{...}是定义正则表达式文字( /.../ )的另一种方式,它在这里很有帮助,所以你不需要转义斜杠; looks a bit cleaner...看起来干净了一些...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM