【发布时间】:2014-11-25 12:41:09
【问题描述】:
我正在尝试使用这个 RegEx 搜索:<div class="ms3">(\n.*?)+<in Ruby,但是一旦我到达最后一个字符“<div class="ms3">(\n.*?)+ 时,它会打印出<div class="ms3">,这正是我正在寻找的,但是一旦我添加了“
我的代码:
#!/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 是 <div class="ms3">(\n.*?)+<\/div> 它选择了第一部分,没有别的
【问题讨论】:
-
除了Don't parse HTML with regex!,您还省略了 multiline 修饰符:
...grep(/.../m)。 -
我很喜欢这种咆哮,并将牢记在心。但是,我不能 100% 确定我正在做的是解析(如果我理解正确的解析)我想要做的就是将某些包含 HTML 的文本从一个 txt 文件提取到另一个,就是这样。除非这正是解析是什么?我没有尝试处理或修改 HTML,最终结果将在另一个程序中完全没有正则表达式的情况下工作
-
@RebekahParsons - 如果你确切地知道你有什么,你可以在提取部分 HTML 时使用正则表达式,但它很容易被破坏 - 例如想象一下:
<div class="ms3">This is some text with <div class="sub">sub div</div> in the middle</div> -
@UriAgassi 啊,我明白你的意思,是的,这可能很狡猾,谢天谢地,我确切地知道我需要什么,并且有不同版本的搜索来弥补不匹配的位我需要。但这是一个很好的观点,那么作为程序的一部分你会用什么来做呢?