Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a dynamic regular expression in Ruby

Tags:

regex

ruby

People also ask

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

How will you create a dynamic regexp using string in a variable?

Here's an example: var stringToGoIntoTheRegex = "abc"; var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g"); // at this point, the line above is the same as: var regex = /#abc#/g; var input = "Hello this is #abc# some #abc# stuff."; var output = input. replace(regex, "!!"); alert(output); // Hello this is !!

What is =~ in Ruby?

=~ 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.

What is match method in Ruby?

Ruby | Regexp match() function Regexp#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.


You can use #{} just like in a string.

1.9.2p290 :001 > some_string = "033112"
 => "033112" 
1.9.2p290 :002 > a_regex = /[A-Z]{1,4}#{some_string}[A-Z]{1-5}-EQB.html/
 => /[A-Z]{1,4}033112[A-Z]{1-5}-EQB.html/ 

I fully support Isaac's solution, but you can also:

a = "\/static\/workout\/[A-Z]{1,4}" + "033112" + "[A-Z]{1,5}-EQB.html"
regex = Regexp.new(a)
stringtomatch =~ regex