sha
sha

Reputation: 55

How to extract a number using regular expression in ruby

I am new to regular expressions and ruby. below is the example which I start working with

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 "

I want to extract boy 1233 6F74 .. to .. D242g in an array Similarly I want to extract girl Aui817E 9AD453 .. to .. 43ADAC0 1AADS4D8 BASAA24 in an array

I did tried to this could not do it. Can some one please help me to this simple exercise. Thanks in advance.

begin
     pattern = /apple\[\d+\]: \{\d+\} (\w) (\d+) (\d+) /
      f = pattern.match(words)
      puts " #{f}"
end

Upvotes: 1

Views: 70

Answers (2)

riocampos
riocampos

Reputation: 101

array = words.scan(/apple\[\d+\]: {\d+}(.+)/).flatten.map { |line| line.scan(/\w+/) }

({ and } are not need to escape on regex.)

return

[
  ["boy", "1233", "6F74", "2AC", "28458", "1594", "6532", "1500", "D242g"],
  ["girl", "Aui817E", "9AD453", "91321SDF", "3423FS", "1213FDAS", "110FADA4", "43ADAC0", "1AADS4D8", "BASAA24"]
]

array[0] gives an array start with "boy", and array[1] gives an array start with "girl".

Upvotes: 0

sawa
sawa

Reputation: 168269

words.scan(/apple\[\d+\]: \{\d+\}(.+)/).map{|a| a.first.scan(/\S+/)}

or

words.each_line.map{|s| s.split.drop(2)}

Output:

[
  ["boy", "1233", "6F74", "2AC", "28458", "1594", "6532", "1500", "D242g"],
  ["girl", "Aui817E", "9AD453", "91321SDF", "3423FS", "1213FDAS", "110FADA4", "43ADAC0", "1AADS4D8", "BASAA24"]
]

Upvotes: 2

Related Questions