2

How to convert string "/russia/i" to regular expression /russia/i.

I know about Regexp.new str and /#{str}/, but this does not work in case of modifier.

3 Answers 3

4

If you can trust your input:

str = "/russia/i"
re = eval(str) # => /russia/i
Sign up to request clarification or add additional context in comments.

1 Comment

+1 This is one of those times that eval is a good way to go. I don't normally like it that much, but it's straight-ahead, very clear and maintainable. As always, the caveats about using eval with a string the user could have supplied applies.
2

I like this solution

str = "/russia/i"
re = Regexp.new *str.split('/').slice(1,2)
# => /russia/i

1 Comment

we are on the same page!! :))
2
s = "/russia/i"
Regexp.new(s[1..s.rindex('/') - 1],s[-1]) # => /russia/i

or

s = "/russia/i"
s.split("/") # => ["", "russia", "i"]
Regexp.new(s.split("/")[1],1) # => /russia/i

or

s = "/russia/i"
s.split("/") # => ["", "russia", "i"]
Regexp.new(*s.split("/")[1..-1]) # => /russia/i

2 Comments

Don’t the first two assume that the modifier is always i though?
@AndrewMarshall You are right,but that's the way I reached to the last(better) solution although.Thus didn't delete those. :)

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.