Home »
Ruby programming
Regular Expressions in Ruby
Ruby regular expressions: Here, we are going to learn about the regular expressions, what is it, operators which are used in it with syntax and examples.
Submitted by Hrithik Chandra Prasad, on September 04, 2019
Ruby regular expressions
Regular expressions are a series of characters which are used to define the pattern to carry out a specific search. It can also be termed as a kind of language which tells the text pattern. It is also known by regexp. Forward slashes are used for writing the pattern.
The basic syntax of regex looks like:
/search string/
To conduct pattern matching, you will have to use ~= or #match operator. Now let us understand each of the methods broadly.
~= operator
It is a basic pattern matching operator which consumes two operands namely pattern or regular expression and a string. No doubt, the regexp is matched with the string. The operator returns integer value if the pattern is matched otherwise nil. That integer value is nothing but the index of the first match. Let us understand the working of ~= operator with the help of a supporting example:
Example:
=begin
Ruby program to demonstrate use of ~= operator.
=end
str1 = "Dreams are not those which we see in night but they are those which do not let us sleep.";
str2 = "Little failures makes you one step closer to success.";
if ( str1 =~ /Dreams/ )
puts "First string is related to Dreams"
end
if ( str2 =~ /failures/ )
puts "Second string is related to success"
end
Output
First string is related to Dreams
Second string is related to success
If you have gone through the working of .include? method then you can relate the similarity between the working of both.
#match operator
The match operator matches the regular expression or pattern with the specified string and returns an instance of class MatchData if the pattern is matched otherwise returns nil.
Let us go through its implementation with the help of a Ruby code.
=begin
Ruby program to demonstrate use of match operator.
=end
str1 = "Dreams are not those which we see in night but they are those which do not let us sleep."
str2 = "Little failures makes you one step closer to success."
puts /Dreams/.match(str1)
puts /failures/.match(str2)
Output
Dreams
failures
You must be thinking that it is returning string but in actual, it is returning an object of class MatchData.
Now, let us get some knowledge about Regular Expression Modifies which are mentioned below with their description in brief.
- i – i modifier ignores case (uppercase or lowercase) while matching the text.
- o – It is used to perform #{} interpolations but only one time when the first time literal pattern is checked.
- x – It permits comments to be included in the regexp. It also ignores white spaces during evaluation.
- m – It matches multiple lines and understands the newline as a normal character.