【问题标题】:RegEx code works in theory but not when code is runRegEx 代码在理论上有效,但在运行代码时无效
【发布时间】:2014-11-25 12:41:09
【问题描述】:

我正在尝试使用这个 RegEx 搜索:&lt;div class="ms3"&gt;(\n.*?)+&lt;in Ruby,但是一旦我到达最后一个字符“<div class="ms3">(\n.*?)+ 时,它会打印出&lt;div class="ms3"&gt;,这正是我正在寻找的,但是一旦我添加了“

我的代码:

#!/usr/bin/ruby
# encoding: utf-8

File.open('ms3.txt', 'w') do |fo|
  fo.puts File.foreach('input.txt').grep(/<div class="ms3">(\n.*?)+/)
end

我正在搜索的一些内容:

  <div class="ms3">
    <span xml:lang="zxx"><span xml:lang="zxx">Still the tone of the remainder of the chapter is bleak. The</span> <span class="See_In_Glossary" xml:lang="zxx">DAY OF THE <span class="Name_Of_God" xml:lang="zxx">LORD</span></span> <span xml:lang="zxx">holds no hope for deliverance (5.16–18); the futility of offering sacrifices unmatched by common justice is once more underlined, and exile seems certain (5.21–27).</span></span>
  </div>

  <div class="Paragraph">
    <span class="Verse_Number" id="idAMO_5_1" xml:lang="zxx">1</span><span class="scrText">Listen, people of Israel, to this funeral song which I sing over you:</span>
  </div>

  <div class="Stanza_Break"></div>

我需要做的完整的 RegEx 是 &lt;div class="ms3"&gt;(\n.*?)+&lt;\/div&gt; 它选择了第一部分,没有别的

【问题讨论】:

  • 除了Don't parse HTML with regex!,您还省略了 multiline 修饰符:...grep(/.../m)
  • 我很喜欢这种咆哮,并将牢记在心。但是,我不能 100% 确定我正在做的是解析(如果我理解正确的解析)我想要做的就是将某些包含 HTML 的文本从一个 txt 文件提取到另一个,就是这样。除非这正是解析是什么?我没有尝试处理或修改 HTML,最终结果将在另一个程序中完全没有正则表达式的情况下工作
  • @RebekahParsons - 如果你确切地知道你有什么,你可以在提取部分 HTML 时使用正则表达式,但它很容易被破坏 - 例如想象一下:&lt;div class="ms3"&gt;This is some text with &lt;div class="sub"&gt;sub div&lt;/div&gt; in the middle&lt;/div&gt;
  • @UriAgassi 啊,我明白你的意思,是的,这可能很狡猾,谢天谢地,我确切地知道我需要什么,并且有不同版本的搜索来弥补不匹配的位我需要。但这是一个很好的观点,那么作为程序的一部分你会用什么来做呢?

标签: ruby regex


【解决方案1】:

您的问题从使用File.foreach('input.txt') 开始,它将结果分成几行。这意味着该模式分别与每一行匹配,因此没有一行与该模式匹配(根据定义,所有行的中间都没有\n)。

你应该有更好的运气阅读整个文本作为一个块,并在上面使用match

File.read('input.txt').match(/<div class="ms3">(\n.*?)+<\/div>/)
# => #<MatchData "<div class=\"ms3\">\n    <span xml:lang=\"zxx\">
# => <span xml:lang=\"zxx\">Still the tone of the remainder of the chapter is bleak. The</span> 
# => <span class=\"See_In_Glossary\" xml:lang=\"zxx\">DAY OF THE 
# => <span class=\"Name_Of_God\" xml:lang=\"zxx\">LORD</span></span> 
# => <span xml:lang=\"zxx\">holds no hope for deliverance (5.16–18); 
# => the futility of offering sacrifices unmatched by common justice is once more 
# => underlined, and exile seems certain (5.21–27).</span></span>\n  </div>" 1:"\n  ">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 2013-10-14
    相关资源
    最近更新 更多