[英]Ruby Script to Process each line in an SQL file
我在编写此脚本时遇到了问题,以检查.sql文件并替换某些字符串内容。 例如
我正在尝试替换:
result of using this information. If you have any comments, queries or concerns with regards to the above information,
Please <a href="#" target="_blank">Click Here</a> for different contact options.</p>
<h4>Stone properties:</h4>
<p><span>Scientific name of the stone:</span> Quartz/Silicon dioxide</p>
<p><span>Group:</span> Silicates – tektosilicates</p>
看起来像1000条数据库行:
Please <a href="#" target="_blank">Click Here</a> for different contact options.</p>
<ul class="navlistjdxcms">
<h4>Stone properties:</h4>
<li><span>Scientific name of the stone:</span> Quartz/Silicon dioxide</li>
<li><span>Group:</span> Silicates – tektosilicates</li>
想法是匹配HTML标记,然后更改标记并添加CSS类,而无需更改数据库文件中的其他文本/行。 到目前为止,我已经提出了:
full_path_to_read = File.expand_path('C:\Users\huber\Desktop\RubyReg\cms_page.sql')
full_path_to_write = File.expand_path('C:\Users\huber\Desktop\RubyReg\cms_page2.sql')
stringla = ""
File.open(full_path_to_read).each_line { |s|
contents = s
xyz = contents.scan(/<p><span>.*?<\/span>.*?<\/p>/o)
new_str = xyz.to_s.gsub('<p>', '<li>')
new_str2 = new_str.gsub('</p>', '</li>')
new_string = '<ul class="navlistjdxcms">' + new_str2 + '</ul>'
m = s.gsub((/<p><span>.*?<\/span>.*?<\/p>/o), "#{new_string}")
stringla += m
}
File.open(full_path_to_write, "w+") { |f| f.write(stringla) }
但似乎正在
<ul class="navlistjdxcms">
针对以下项的每次匹配显示
/<p><span>.*?<\/span>.*?<\/p>/o
在文件中。
我尝试了许多Ruby regex表达式,并尝试直接连接到数据库以从那里更改数据库,但是似乎无法弄清楚。
我也尝试使用:
m = s.gsub("#{xyz}", "#{new_string}")
以及其他许多变体,但都没有成功。 我该怎么做,以便用new_string替换整个匹配的段落,而不仅仅是单个匹配的行? 我也感觉到我在这里用Ruby字符串和类做其他事情。
我知道这是Ruby Regex 101,似乎无法弄清楚。 提前谢谢了。
您正在呼叫each_line
因此一次只能获得一条线路。 鉴于此,我相信很清楚为什么您看到自己看到的结果。
由于只有1000个这样的部分,因此您可以读取整个文件,并使用捕获组进行全局替换以获得所需的结果。
我无法让regex在支持替换的regexplanet上运行,但是您可以在http://rubular.com/r/ahSEerTEnW上看到匹配组。 进行匹配后,可以使用文字和匹配组引用(\\ 1,\\ 2,\\ 3,\\ 4)组合构造新的替换文本,如下所示:
\1
<ul class="navlistjdxcms">
\2
<li>\3</li>
<li>\4</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.