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.