Is there any way to convert String to Regexp (in Ruby)? Let's say:
'example' ---> /example/
My purpose is generating Regexps dynamically.
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.
=~ 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.
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.
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.
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)}/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With