0

I thought this question could be interesting to put it up here.

For example I have a string for search query like: "hello world"

There could be strings like this:

Hello World
Hello-world
hello!! world

How could you write an expression that will dynamically match these? If the expression works, it should works on this too:

Search: "Hi pals!"

Hi pals
Hi! Pals!
Hi-pals

Is it possible?

DucDigital
  • 4,580
  • 9
  • 49
  • 97

2 Answers2

3

Sure, you could do something like this:

/hi.*?pals/i

the trailing i at the end enables case-insensitive matching, and the .*? matches any characters (except line breaks) between the "hi" and "pals".

A Rubular demo: http://rubular.com/r/cwtbV2iTwy

Beware that it also matches a string like "Himalaya pals":

Himalaya pals
^^       ^^^^

If you don't want that to happen, add some word-boundaries in the mix:

/\bhi\b.*?\bpals\b/i
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • is there a way to make it dynamic? this will definitely not match hello world – DucDigital Jul 31 '11 at 09:47
  • Well, you can do it like this: `/hi.*?pals|hello.*?world/i` to match both of the two greetings. Not sure what you mean by _dynamic_ though... – Bart Kiers Jul 31 '11 at 09:48
2

Presumably you don't want "hi pals" to match "chi palsy", either, right? Seems like you're trying to find strings that have the same words as your input. If so, here's a way:

class String
  def words
    scan(/\w+/).map(&:downcase)
  end
end

a = ["Hi pals", "Hi, pals", "hi-pals", "hi! ? pals?", "hipals", "himalaya pals"]
search = "hi pals"

a.select {|test| test.words == search.words}

=> ["Hi pals", "Hi, pals", "hi-pals", "hi! ? pals?"]
glenn mcdonald
  • 15,290
  • 3
  • 35
  • 40