pjuzeliunas
pjuzeliunas

Reputation: 1656

Ruby: generating new Regexps from strings

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

Answers (3)

Staffan Nöteberg
Staffan Nöteberg

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

sawa
sawa

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

kurumi
kurumi

Reputation: 25599

you can try /#{your variable}/

Upvotes: 2

Related Questions