请逐行读取一个文件(C:\1.txt)的文本,用正则表达式"include.*?xercesc.*?>"匹配每一行,如果匹配成功,则将这一行中的从“<”到“/”的字符串和“>”替换成“"”,失败则保持原样,最后将这一行的文本写入文件C:\2.txt中。
fin = File.new("C:\\1.txt")tmp = []fin.each_line do |line| if line =~ /include.*?xercesc.*?>/ line.sub!(/(.*)<.*\/(.*?)>(.*)/, '\1"\2"\3') end tmp << lineendfin.close# puts tmp.join()fout = File.new("C:\\2.txt", "w")fout.write(tmp.join())fout.close测试输入文件1.txt:this is the first line</include abc_xercesc.h>xy <aaa/include 123_xercesc.c> zd测试输出文件2.txt:this is the first line"include abc_xercesc.h"xy "include 123_xercesc.c" zd