Question

I got a variable string which equals shid!

I'd like a regular expression that renders true if the inputed string matches every character of the previous variable string in the good order.

As I always fail to explain properly what I want to do, here is an example of possible inputs and outputs:

  • shid! returns true
  • shid returns false
  • shhhhiddd! returns true
  • ssssshhhhiiiiiddd!!!! returns true
  • hsid! returns false

For the ritual question "What did I try", I'm not used to regular expression. So my answer would be this: "shid!" =~ /s.*!/, and obviouly this isn't the good answer and I know why, but don't know how to fix it. Thanks for the kind help

Était-ce utile?

La solution

Try:

string = 'shid!'
reg = Regexp.new string.split('').join('+')


!!('shid!' =~ reg)    #=> true
!!('shid' =~ reg)     #=> false
!!('shhhhiddd!' =~ reg) #=> true
!!('ssssshhhhiiiiiddd!!!!' =~ reg)  #=> true
!!('hsid!' =~ reg) #=> false

Autres conseils

You can do using #squeeze

str.squeeze == 'shid!' #=> true

I'm not sure I've got the question. But maybe it's what you are looking for:

str = 'ssssshhhhiiiiiddd!!!!'
str.split('').uniq.join == 'shid!' #=> true
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top