Working with Regular Expressions in Ruby

Ruby uses the =~ operator to check any given string against regular expression. For example, a string “This is my 1 string” can be used with =~ in the following way

string = 'This is my string of 17-char'
if string =~ /([0-9]+)-char/ && $1.to_i == string.length
 " #$1 characters in that string."
end

Alternatively, you can use Regexp.match such as

String-match = Regexp.compile( ‘([0-9]+)-char’).match(string)
if match && match[1].to_i == string.length
" #$1 characters in that string."
end

Regular expressions in ruby is a powerful addition for string manipulation and Ruby utilizes RegExp to achieve developer’s objective. Ruby provides several modifies when using Regex including

Regexp::IGNORE: i – makes case insensitive

Regexp::MULTILINE: m – treat lines break like any other string char

Regexp::EXTENDED: x – let you space our Regex with spaces

Example of these modifies are presented below

/something/mix Regexp.new('something', Regexp::EXTENDED + Regexp::IGNORECASE + Regexp::MULTILINE) %r{something}mix

Regular Expressions in Ruby used for such mundane tasks as email address validation, address and zip code validation, telephone format validation, web address validation among others.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…