input_path = "chapter1.xhtml"
output_path = "new.txt"
#input = 'input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">'
string_to_replace = 'bolum1'
File.open(output_path, "w") do |output|
File.open(input_path, 'r') do |f|
f.readlines.each do |line|
counter = 0
# result = input.gsub(string_to_replace) do |match|
result = line.gsub(string_to_replace) do |match|
# puts "found=#{match}"
counter += 1
match[-1, 1] = counter.to_s # replace last char by counter
# puts "replace=#{match}"
match # the result of the block replaces the matched string
end
p result
output.write(result)
end
end # input file will automatically be closed at the end of the block
end # output file will automatically be closed at the end of the block
文件 chapter1.xhtml :
input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">
input file <section id="bolum1"> <section id="bolum1"> <section id="bolum1">
执行 :
$ ruby -w t.rb
"input file <section id=\"bolum1\"> <section id=\"bolum2\"> <section id=\"bolum3\">\n"
"input file <section id=\"bolum1\"> <section id=\"bolum2\"> <section id=\"bolum3\">"
我不确定这是正确的解决方案,因为我不知道您的意见。是 XML 吗?使用适当的 XML 库可能会更好。它更复杂吗?也许输入必须用语法解析。请参阅 www.antlr4.org 和http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference。本书的源代码是免费的,并且包含解析 XML 的语法。
希望有帮助。乙