2

My code will receive a parameter containing a string representation of a regular expression. It is probable that the strings would be like "/whatever/" with slashes at the beginning and end. Given a string,

str = "/^foo.*bar$/"

I would like to create a regular expression from that string.

When I do:

pat = Regexp.new(str)
# => /\/^foo.*bar$\//
pat.match "foolishrebar"
# => nil

all of the special characters are quoted. I have not figured out how not to quote the string.

When I create a pattern directly with /pattern/, it works fine.

pat = /^foo.*bar$/
pat.match "foolishrebar"
# => #<MatchData "foolishrebar">
2
  • 3
    As an aside, you almost always want \A and \z (beginning/ending of string) instead of ^ and $ (beginning/ending of line) in Ruby. Commented Jan 28, 2019 at 18:14
  • If you really mean what you are asking for, then you can do eval(str). But I am not posting this as an answer because I know that there are stupid people around who would downvote such an answer as soon as I post one. Commented Jan 29, 2019 at 4:38

2 Answers 2

4

When you use Regexp.new, don't start and end your string with /. Just let str = '^foo.*bar$'. The only things being escaped are the beginning and ending slashes; the metacharacters are fine.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, I can use str.tr( '/', '') to remove any slashes from the string before passing it to Regexp.new.
0
str = '^foo.*bar$'

r = /#{str}/
  #=> /^foo.*bar$/ 

"foolishly, the concrete guy didn't use rebar".match?(r)
  #=> true

Comments

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.