从Ruby中的数据中提取特定字段
这是一个Ruby程序,我必须在其中使用正则表达式从文件中的数据提取特定字段。 文件中的数据采用以下格式: 11月13日01:46:57 10.232.47.76 qas-adaptiveip-10-232-47-76 2015-11-13 01:46:57+0000[信息]:qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d已在adap_tdagt注销 我需要提取以下值 1)2015-11-13 01:46:57 +0000 2) qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d 我已经写了代码,但它不能正常工作。有人能帮我解决这个问题吗从Ruby中的数据中提取特定字段,ruby,regex,Ruby,Regex,这是一个Ruby程序,我必须在其中使用正则表达式从文件中的数据提取特定字段。 文件中的数据采用以下格式: 11月13日01:46:57 10.232.47.76 qas-adaptiveip-10-232-47-76 2015-11-13 01:46:57+0000[信息]:qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d已在adap_tdagt注销 我需要提取以下值 1)2015-11-13 01:46:57 +0000 2) qas-296d1fa95
class Task5
def initialize
# @f=File.open('C:/Users/aroraku/Desktop,boc-adap_td-agent.log-2.log',r)
@count=0
end
def check_line(line)
if(line=~/deregistered adap_tdagt$/)
line=~ (/.*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} +\d{4})/)
puts "#{$1}"
end
end
def file_read
open("boc-adap_td-agent.log-2.log") { |f|
while line=f.gets do
check_line(line)
end
}
# return @count
end
end
您必须为日期转义
+
签名:
line =~ /.*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \+\d{4}).+([a-z]{3}-[a-f0-9]{40})/
puts $1 # 2015-11-13 01:46:57 +0000
puts $2 # qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d
由于您的代码的问题已经确定,我想建议从每行中提取所需信息的另一种方法:
r = /
(?: # begin a non-capture group
\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\s\+\d{4} # match date string
) # end non-capture group
| # or
(?: # begin a non-capture group
(?<=\[info\]:\s) # match "[info:] " in a positive lookbehind
\S+ # match >= 1 characters other than whitespace
) # end non-capture group
/x # extended/free-spacing regex definition mode
str.scan(r)
#=> ["2015-11-13 01:46:57 +0000", "qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d"]
r=/
(?:#开始一个非捕获组
\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\s\+\d{4}匹配日期字符串
)#结束非捕获组
|#或
(?:#开始一个非捕获组
(?=除空格外的1个字符
)#结束非捕获组
/x#扩展/自由间距正则表达式定义模式
str.scan(r)
#=>[“2015-11-13 01:46:57+0000”,“qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d”]
您需要解释您对字符串的了解。它是否始终包含“[info]:”
在两个感兴趣的字段之间?要捕获的非日期是否始终位于字符串的末尾?如果字符串包含多个符合条件的子字符串,是否要将其全部提取?请通过编辑问题进行澄清。是的,字段将始终与示例中所示的字段相同…谢谢,我希望提供一个关于如何改进问题的几点建议。(不过,现在不要更改。)首先,我确信您知道如何将文本文件读入字符串,因此最好围绕字符串来构建问题,而不要参考它来自何处。其次,您的示例数据应该始终是有效的Ruby对象,每个对象的值由您定义的变量保存;例如,str=“Nov 13…adap_tdagt”
。这样,读者就可以在注释和答案中引用这些变量(此处为str
),而无需定义它们。
r = /
(?: # begin a non-capture group
\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\s\+\d{4} # match date string
) # end non-capture group
| # or
(?: # begin a non-capture group
(?<=\[info\]:\s) # match "[info:] " in a positive lookbehind
\S+ # match >= 1 characters other than whitespace
) # end non-capture group
/x # extended/free-spacing regex definition mode
str.scan(r)
#=> ["2015-11-13 01:46:57 +0000", "qas-296d1fa95fd0ac5a84ea73234c0c48d64f6ea22d"]