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,519
  • 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
  • 160,959
  • 41
  • 265
  • 366
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
  • 3,995
  • 1
  • 18
  • 17
2

you can try /#{your variable}/

kurumi
  • 24,217
  • 4
  • 43
  • 49