jackneedshelp
jackneedshelp

Reputation: 137

How do I use regular expression to select from an array?

I have a code that asks for the user to either type Cats or Dogs then it'll search an array for everything that contains the word Cats or Dogs then puts them all out.

print "Cats or Dogs? "
userinput = gets.chomp

lines = [["Cats are smarter than dogs"],["Dogs also like meat"], ["Cats are nice"]]

lines.each do |line|
  if line =~ /(.*?)#{userinput}(.*)/
    puts line
  end
end

So If I were to input Cats. I should get two sentences:

Cats are smarter than dogs
Cats are nice

You could even input smarter and I'll get

Cats are smarter than dogs

I'm strictly looking for ways to use an regular expression to search through an array or string and take out the lines/sentences that match the expression.

If anyone is wondering, the lines array was originally from an file and I turned each line into an array part.


EDIT:

Wow, how far I came in the coding world.

print "Cats or Dogs? "
userinput = gets.chomp

lines = [["Cats are smarter than dogs"],["Dogs also like meat"], ["Cats are nice"]]

lines.each do |linesInside|
  linesInside.each do |line|
    if line =~ /(.*?)#{userinput}(.*)/
      puts line
    end
  end
end

Took literally 5 seconds to solve what took me ages to give up on at the time.

Upvotes: 2

Views: 577

Answers (3)

Eric Duminil
Eric Duminil

Reputation: 54223

Since your array is an array of arrays, you could call flatten first :

lines.flatten.grep(/#{userinput}/i)

i is for case insensitive search, so that 'Dogs' matches 'Dogs' and 'dogs'.

If you want whole-word search :

lines.flatten.grep(/\b#{userinput}\b/i)

Finally, if you don't really need an array of arrays, just read an array from your file directly, either with File.readlines(f) or File.foreach(f).

Upvotes: 0

akuhn
akuhn

Reputation: 27793

Try this

...
lines = ["Cats are smarter than dogs", "Dogs also like meat", "Cats are nice"]
regexp = Regexp.new(userinput)
selected_lines = lines.grep(regexp)
puts selected_lines

How does this work?

  • grep filters an array using pattern matching
  • Notice that I am using an array of strings. Your example code uses an array of single-element arrays, I assume you mean to just use an array of strings.

Upvotes: 2

Cary Swoveland
Cary Swoveland

Reputation: 110675

You can, of course, do that without a regex.

lines = ["Dogs are smarter than cats", "Cats also like meat", "Dogs are nice"]

print "Cats or Dogs? "
input = gets.chomp.downcase

If input #=> "dogs",

lines.select { |line| line.downcase.split.include?(input) }
  #=> ["Dogs are smarter than cats", "Dogs are nice"]

If input #=> "cats",

lines.select { |line| line.downcase.split.include?(input) }
  #=> ["Dogs are smarter than cats", "Cats also like meat"]

Upvotes: 1

Related Questions