Reputation: 1656
Is there any way to convert String to Regexp (in Ruby)? Let's say:
'example' ---> /example/
My purpose is generating Regexps dynamically.
Upvotes: 13
Views: 5922
Reputation: 4145
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.
Upvotes: 4
Reputation: 168101
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)}/
Upvotes: 18