Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: generating new Regexps from strings

Tags:

string

regex

ruby

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

'example' ---> /example/

My purpose is generating Regexps dynamically.

like image 666
pjuzeliunas Avatar asked Mar 24 '11 00:03

pjuzeliunas


People also ask

How do you extract a substring from a string in Ruby?

There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

How do you match a string in Ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.

How do you replace a string in Ruby?

Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.


1 Answers

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)}/
like image 130
sawa Avatar answered Oct 01 '22 14:10

sawa