Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Ruby Regex or Regular Expression in a variable

Posted on August 12, 2021August 12, 2021 by admin

Overview

In Ruby, a regular expression is defined between two forward slashes. This is a way to differentiate a regular expression from a normal string. This is how a regex will be represented

/#{regex}/

As such it is also possible to assign a Regular Expression to a variable. Below is the example program for the same.

Program

regex = "b+"

input = "bb"
match = input.match(/#{regex}/)
puts match

input = "bbb"
match = input.match(/#{regex}/)
puts match

input = "a"
match = input.match(/#{regex}/)
puts match

Output

bb
bbb

Notice how we are assigning the regular expression to a variable like this

regex = "b+"

And then using it in the match like this

match = input.match(/#{regex}/)

Other than regex you can have other variables or any kind of string

For example

regex = "b+"
input = "abb"
match = input.match(/a#{regex}/)
puts match

Notice the regex here we prefixed it with the character “a”

/a#{regex}/

Now run the above program. It will give a match

abb
  • regex
  • ruby
  • ©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme