首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RegEx代码在理论上起作用,但在运行代码时不起作用。

RegEx代码在理论上起作用,但在运行代码时不起作用。
EN

Stack Overflow用户
提问于 2014-11-25 12:41:09
回答 1查看 55关注 0票数 0

我正在尝试使用这个RegEx搜索:<div class="ms3">(\n.*?)+<,但是,当我到达最后一个字符"<“时,它就完全停止工作了。我在Rubular中对它进行了测试,RegEx运行得非常好,我使用rubymine编写代码,但我也使用Powershell对它进行了测试,得到了相同的结果。没有错误信息。当我运行<div class="ms3">(\n.*?)+时,它会打印<div class="ms3">,这正是我所要寻找的,但是只要我添加"<“,它就什么都没有了。

我的代码:

代码语言:javascript
复制
#!/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

我正在寻找的一些东西:

代码语言:javascript
复制
  <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>,它选择了第一节,而没有其他内容。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-25 12:53:21

您的问题首先是使用File.foreach('input.txt'),它将结果分割成行。这意味着模式分别与每一行相匹配,因此没有一个行与模式匹配(根据定义,没有一个行的中间有\n )。

您应该更幸运地将整个文本作为一个块阅读,并在其中使用match

代码语言:javascript
复制
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  ">
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27127071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档