Javatpoint Logo
Javatpoint Logo

Ruby Regular Expression

A regular expression is also spelled as regexp which holds a regular expression, used to match a pattern against strings. In Ruby, a pattern is written between forward slash characters. They describe the content of a string. Ruby regular expression is more similar to Perl regular expression.


Ruby 1.9 uses Oniguruma regular expressions library but Ruby 2.0 uses Onigmo regular expressions library. Onigmo is a fork library of Oniguruma adding some new features.

=∽ and #match operators

The pattern matching is achieved by using =∽ and #match operators.


This is the basic matching pattern. Here two operands are used. One is a regular expression and other is a string. The regular expression is matched with the string.

If a match is found, the operator returns index of first match otherwise nil.


Ruby Regular expression 1


This operator returns a MatchData object on matching otherwise nil.

Ruby Regular expression 2

Metacharacters and Escapes

Metacharacters have specific meaning in a pattern. To match a string, they are back slashed (\\\) or escaped. Some meta characters are (,), (.), (?), (+), (-), (*), [,], {,}.

It returns the specific string when matched otherwise nil.


Ruby Regular expression 3

Characters Classes

Metacharacters have specific meaning in a pattern. To match a string, they are back slashed (\\\) or escaped.

A character class is encircled within square brackets.


Here, [ab] means a or b. It is the oppoite of /ab/ which means a and b.


Ruby Regular expression 4


Here, [a-d] is equivalent to [abcd]. The hyphen (-) character class represents range of characters.


Ruby Regular expression 5


The ^ sign represents any other character which is not present in the range.


Ruby Regular expression 6


Characters defined till now match a single character. With the help of repetition metacharacter, we can specify how many times they need to occur. These meta characters are called quantifiers.

  • *: Zero or more times
  • +: One or more times
  • ?: Zero or one times (optional)
  • {n}: Exactly n times
  • {n, }: n or more times
  • {,m}: m or less times
  • {n,m}: At least n and at most m times


Ruby Regular expression 7


Grouping uses parentheses to group the terms together. Grouping the terms together make them one.


Ruby Regular expression 8

In this example, first pattern matches a vowel followed by two characters.

In the second pattern, it matches a vowel followed by a word character, twice.


This expression provides grouping without capturing. It combines term without creating a backreference.


Ruby Regular expression 9

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA