Is there any way to convert String to Regexp (in Ruby)? Let's say:
'example' ---> /example/
My purpose is generating Regexps dynamically.
Is there any way to convert String to Regexp (in Ruby)? Let's say:
'example' ---> /example/
My purpose is generating Regexps dynamically.
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)}/
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.