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\">"
我不確定這是否是正確的解決方案b因爲我不知道你的意見。它是XML嗎?使用適當的XML庫可能會更好。它更復雜嗎?也許輸入必須用的語法進行解析。請參閱www.antlr4.org和http://pragprog.com/book/tpantlr2/the-definitive-antlr-4-reference。這本書的源代碼是免費的,包含語法解析XML。
希望有所幫助。 B
代碼正在工作,但它不這樣做,我希望 – SemihY
給我三行輸入文件,我忍不住沒有更多的信息。 – user1852994
輸入文件 <節ID = 「bolum1」> <節ID = 「bolum1」> 欲 <節ID = 「bolum1」> <節ID = 「bolum2」> – SemihY