regular expressions

Regular expressions can help enforce that particular pattern. If the user’s pattern does not match our format, then using regular expressions, we can reject that data.

A regular expression starts with / and ends with /. The following is a regular expression:

/ \d /

Here \d has a special meaning. It stands for any digit. Let’s try to make use of it and the meaning will become much clearer. Let’s say that we want to check if a number is at least a three digit number or not. This is what we can do:

regex = /\d\d\d/
word = "123"
puts "nice" if word =~ regex  // nice

The order number of a shipping company starts with two digits. We want our regular expression to check that.

regex = /\d\d/ // also can write regex = /\d{2}/
word1 = "68PEJRT"  #=> true
puts "word1 is a match!" if word1 =~ regex

word3 = "TGF8J6D"  #=> false
puts "word3 is a match!" if word3 =~ regex