Learn Ruby
Regular expressions

\d to match any digit

In USA the phone numbers follow a pattern. The pattern is like this.


When we ask user to enter their phone number they can enter their phone number in following ways.

  • 789-3459876
  • 7893459876
  • 786 345 9876
  • 789.345.9876

All of the above are not matching with the format in which we want the data. Regular expression can help enforce a particular pattern. If the pattern is not matching then using regular expression we can reject that data.

A regular expression starts with / and ends with /. Following is a regular expression.


Here /d has a special meaning. It stands for any digit. Let’s try to make use of it.

Let’s say that we want to check if a number is a three digit number or not. This is what we can do.

Ruby allows us to use =~ to check if a regular expression is matching with the word or not.

Let’s see one more example. This time we want to see if zipcode 76981 is of five digits or not.