【问题标题】:Ruby Script to Process each line in an SQL file用于处理 SQL 文件中每一行的 Ruby 脚本
【发布时间】:2013-08-21 04:52:11
【问题描述】:

我编写的这个脚本有问题,该脚本用于搜索 .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>&nbsp;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 &ndash; tektosilicates</p>

看起来像跨越 1000 个数据库行:

Please <a href="#" target="_blank">Click Here</a>&nbsp;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 &ndash; 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 正则表达式并尝试直接连接到数据库以从那里更改数据库,但似乎无法弄清楚。

我也尝试过使用:

m = s.gsub("#{xyz}", "#{new_string}")

以及许多其他的变体,但没有取得多大成功。我该怎么做才能用 new_string 替换整个匹配的段落,而不仅仅是单个匹配的行?我也有一些感觉,我在这里对 Ruby 字符串和类做错了什么。

我知道这是 Ruby Regex 101,但似乎无法弄清楚。非常感谢。

【问题讨论】:

    标签: mysql ruby regex gsub


    【解决方案1】:

    您正在调用each_line,因此您一次只能收到一条线路。鉴于此,我相信您很清楚为什么会看到您所看到的结果。

    由于只有 1000 个这样的部分,您可以读取整个文件并使用捕获组进行全局替换以获得您想要的结果。

    我无法让正则表达式在支持替换的 regexplanet 上运行,但您可以在 http://rubular.com/r/ahSEerTEnW 上看到匹配组。完成匹配后,您可以使用结合匹配组引用(\1、\2、\3、\4)的文字构造新的替换文本,如:

    \1
    <ul class="navlistjdxcms">
    \2
    <li>\3</li>
    <li>\4</li>
    

    【讨论】:

    • 我很想了解更多关于捕获组的信息。我已经进行了初步研究并尝试了但没有成功。但是有一个问题,'each_line' 代码是遍历每个单独的 .sql 行还是遍历文件中每一行中的 html '\r\n'?因为我从输出中注意到的问题是 '"#{new_string}"' 替换了 '/

      .*?.*?/ 的每个实例o' 在线上而不是作为一个整体上的那条线?当我尝试 'm = s.gsub(#{xyz}, "#{new_string}")' 尝试解决此问题时,它不起作用?

    • 它遍历文件的每一行,Rocky。至于捕获组,我将开始一个您可以查看的正则表达式小提琴。
    • 查看更新的答案以参考带有捕获组的正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2013-04-09
    • 2014-06-02
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 2013-12-07
    • 2011-01-28
    • 2014-06-14
    相关资源
    最近更新 更多