1

I have a simple requirement. I read a string from user( either track or trAck). I want a logic using Regexp concept which will check this user input against a regular expression (within a string) :

 def test_regex
      string = "tr[Aa]ck"
      string1 = /#{Regexp.quote(string)}/ #tried something here
      user_input = "track" #or "trAck"
      if string1 == user_input
        puts "REGEX works"
      else
        puts "DIDN work"
      end
    end
 end

I know I have blindly written some code. Need the right direction!

1 Answer 1

3

Remove the Regexp.quote, or use Regexp::new. (If you use Regexp.quote, the resulting pattern will match tr[Aa]ck literally)

string1 = /#{string}/
# OR
# string1 = Regexp.new(string)

And use =~ operator instead of == to match the regular expression against string.

if string1 =~ user_input

def test_regex
  string = "tr[Aa]ck"
  string1 = /#{string}/
  user_input = "track" #or "trAck"
  if string1 =~ user_input
    puts "REGEX works"
  else
    puts "DIDN work"
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Works like Charm!! will accept your answer in 10 minutes :) Thanks a lot!!
How can we convert a regex back to string?? Actually I need to combine my regex within a string.
@akshatha, You can use Regexp#source to get back the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.