m0j0
m0j0

Reputation: 3864

Creating a regexp from string without quoting

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">

Upvotes: 2

Views: 68

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

str = '^foo.*bar$'

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

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

Upvotes: 0

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

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.

Upvotes: 4

Related Questions