13

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

'example' ---> /example/

My purpose is generating Regexps dynamically.

pjuzeliunas
  • 1,596
  • 1
  • 15
  • 19

3 Answers3

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)}/
sawa
  • 165,429
  • 45
  • 277
  • 381
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.

Staffan Nöteberg
  • 4,095
  • 1
  • 19
  • 17
2

you can try /#{your variable}/

kurumi
  • 25,121
  • 5
  • 44
  • 52