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を解析するための文法が含まれています。
お役に立てば幸いです。B