我是正则表达式和ruby的新手。下面是我开始使用
的例子words= "apple[12345]: {123123} boy 1233 6F74 2AC 28458 1594 6532 1500 D242g
apple[13123]: {123123123} girl Aui817E 9AD453 91321SDF 3423FS 1213FDAS 110FADA4 43ADAC0 1AADS4D8 BASAA24 "
我想在数组中提取boy 1233 6F74 .. to .. D242g
同样,我想在数组中提取girl Aui817E 9AD453 .. to .. 43ADAC0 1AADS4D8 BASAA24
我确实尝试过这样做不行。有人可以帮我这个简单的练习。 提前致谢。
begin
pattern = /apple\[\d+\]: \{\d+\} (\w) (\d+) (\d+) /
f = pattern.match(words)
puts " #{f}"
end
答案 0 :(得分:2)
words.scan(/apple\[\d+\]: \{\d+\}(.+)/).map{|a| a.first.scan(/\S+/)}
或
words.each_line.map{|s| s.split.drop(2)}
输出:
[
["boy", "1233", "6F74", "2AC", "28458", "1594", "6532", "1500", "D242g"],
["girl", "Aui817E", "9AD453", "91321SDF", "3423FS", "1213FDAS", "110FADA4", "43ADAC0", "1AADS4D8", "BASAA24"]
]
答案 1 :(得分:0)
array = words.scan(/apple\[\d+\]: {\d+}(.+)/).flatten.map { |line| line.scan(/\w+/) }
({
和}
不需要在正则表达式中转义。)
返回
[
["boy", "1233", "6F74", "2AC", "28458", "1594", "6532", "1500", "D242g"],
["girl", "Aui817E", "9AD453", "91321SDF", "3423FS", "1213FDAS", "110FADA4", "43ADAC0", "1AADS4D8", "BASAA24"]
]
array[0]
以" boy"开头给出一个数组,array[1]
给出一个以" girl"开头的数组。