2013-06-22 60 views
0

我在Ruby中的新手。 我有一个样品(输入文本),如:红宝石:复制两行

Message: 
update attributes in file and commit version 
---- 
Modified 

我需要把线上行后“消息”标签。请注意,此行可以与亲近“消息”之类

Message:update attributes in file and commit version 

我已经试过这样:

if line =~/Message/ 

但是,当然,它不会搜索的下一行。

谁能帮我如何捕捉标记之间的“消息”和“---” 如果你知道一些例子,请键入链接

更新行:整个代码

require 'csv' 
data = [] 
File.foreach("new7.txt") do |line| 
    line.chomp! 
    if line =~ /Revision/ 
    data.push [line] 
    elsif line =~ /Author/ 
    if data.last and not data.last[1] 
     data.last[1] = line 
    else 
     data.push [nil, line] 
    end 
    elsif line=~/^Message:(.*)^-/m 
    if data.last and not data.last[2] 
     data.last[2] = line 
    else 
     data.push [nil, nil, line] 
    end 
    end 
end 

CSV.open('new1.csv', 'w') do |csv| 
    data.each do |record| 
    csv << record 
    end 
    enter code here 

输入文件:

Revision: 37407 
Author: imakarov 
Date: 21 июня 2013 г. 10:23:28 
Message:my infomation 
dmitry name 

输出CSV文件: enter image description here

回答

2

您可以使用/^Message:(.*)^---/m为您的正则表达式。 /m允许您跨线边界进行匹配。见http://rubular.com/r/FhqiKx0XyI

更新#1:这是从IRB输出示例:

Peters-MacBook-Air-2:bot palfvin$ irb 
1.9.3p194 :001 > line = "\nMessage:first-line\nsecond-line\n---\nthird-line" 
=> "\nMessage:first-line\nsecond-line\n---\nthird-line" 
1.9.3p194 :002 > line =~ /^Message:(.*)^-/m 
=> 1 
1.9.3p194 :003 > $1 
=> "first-line\nsecond-line\n" 
1.9.3p194 :004 > 
+1

我只是检查和其他类似的问题已经被问过SO /回答。你先搜索了吗?我想知道我们是否应该将其标记为重复或者是否有让您找不到的东西。 –

+0

@PeterAlfin非常感谢你!但它是正确的,如果我用这个表达是这样的:如果行=〜/ ^消息:(*)^ -/Unfortunetely它不工作 –

+0

不,你需要用'M'在表达式的末尾(继尾随斜线)。这是关键的推动因素。 –