13

Is there any way to convert String to Regexp (in Ruby)? Let's say:

'example' ---> /example/

My purpose is generating Regexps dynamically.

3 Answers 3

18
regexp = Regexp.new(string)

or

regexp = /#{string}/

If it is possible that string has special characters, then:

regexp = Regexp.new(Regexp.escape(string))

or

regexp = /#{Regexp.escape(string)}/
Sign up to request clarification or add additional context in comments.

Comments

4

You can also write...

regex = Regexp.compile(string)

...which is a very descriptive name. This method compiles the source code (string) into a nondeterministic finite automaton (regex). The NFA can then be reused over and over.

Comments

2

you can try /#{your variable}/

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.