Home » Ruby Regular Expression

Ruby Regular Expression

by Online Tutorials Library

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.

Syntax:

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.

Example:

Ruby Regular expression 1


#match

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.

Example:

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.

[ab]

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

Example:

Ruby Regular expression 4

[a-d]

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

Example:

Ruby Regular expression 5

[^a-d]

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

Example:

Ruby Regular expression 6


Repetition

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

Example:

Ruby Regular expression 7


Grouping

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

Example:

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.

Example:

Ruby Regular expression 9

You may also like