Updated April 4, 2023
Introduction to Regular Expression in Ruby
Regular Expressions in Ruby are some sequence of characters which are used to search other matches string, for example, if you are searching for the “sofa” in the sentence “sofa is beautiful” then we can use the “sofa is beautiful” =~ /sofa(.*)/ , here we are simply checking if the sofa is available inside the sentence “sofa is beautiful”, so we can understand the importance of the regular expression in Ruby, with the help of regular expression we can search for the very complex string or set of strings also we can use them for validating any request, for example checking if the request string contains given pattern of string then only valid.
Syntax
Below is the syntax for the regular expression in the Ruby. In the given line of code we have written /pattern/, so here we are simply checking for the patter, and in the same block we can specify the ranges for it. For example /\D/ here D means numeric value only. We can also write in the way like /[a-z]/, which means all the lower cases from a to z. We will focus more on the syntax in the example part. The optional check can be used check after all inner pattern completed, here it can be like \D to check known digit.
/search string or pattern/optional check.
Examples to Implement Regular Expression in Ruby
We can use Regular Expressions in the many real-time situations like we can use it when we have to find some specific pattern out of a given sentence, we can use it to replace with match pattern, even we can use it to test if the given string or the set of string falls under the given format. Let us discuss all these situations with one example.
Example #1
Operators used in the given example and their meaning.
- =∽ : here we are using the operator =∽ , this operator contains two things one is a regular expression and another is for matching the string.
- .*: This operators we have used it is checking for the matching of a complete word, * represent to match the complete word like “sofa”, so it should match the complete word “sofa” here.
This is the first example for the Regular Expression in the Ruby below is the explanation for the code. This example is to check if the search string is available inside the sentences.
We have their variables sentence1, sentence2, and sentence3 and all these variables contain sentences. Our goal is to check if the variables containing a sentence are containing a particular word or pattern. Example sofa, car, and city. First, two contain the sofa and car but the sentence3 does not contain the city. In the code below we have prints success for the first two cases and for the second case it fails.
Code:
sentence1 = "This is a very beautiful sofa";
sentence2 = "This is a very beautiful car";
sentence3 = "This is a very beautiful house"
if ( sentence1 =~ /sofa(.*)/ )
puts "sentence1 contains sofa"
end
if ( sentence2 =~ /car(.*)/ )
puts "sentence2 contains car"
end
if (sentence3 =~ /city(.*)/)
puts "sentence3 contains city"
else
puts "The term city is not there in this sentence3"
end
Output:
Example #2
Operators used in these examples are,
- \D(expression): This operator are used for any no-digit, we have many other operators like \d(for any digit),\s(for white space characters),\S(for any nonwhite space characters)
- sub!: This method is used for the string in the Ruby, it makes a copy of all the string occurrences of pattern for the passed second argument to it.
We can explain the below code in the following steps,
We have defined a variable student, it contains the sentence with registration number and a few more details. The registration number is the only numeric value in the given sentence. Here we are fetching the registration number with the help of the sub-method which finds the data from the sentence in the required format which we have passed to it.
Code:
#The student variable contains the student details along with the registration number in the same sentence .
student = "My name is Ranjan Kumar and my registration number is 111100011"
student = student.gsub!(/\D/, "")
puts "Student Registration Number is #{student}"
Output:
Example #3
Operators used for these examples,
- Sub! (method): Return a new string with removing all the other strings according to parameters passed to it in regular expression format.
- /#.*$/(expression): In this expression we are selecting all the attributes after the comment of Ruby and removing all the contents after comment. .* used to select all after specific symbol #.
This example is to fetch the string and numeric both except the sentence start with #. We can explain the below example in the following steps. We have a variable called card which holds the sentence containing card details and few more contents. Here we are using the function sub of Ruby, we are passing pattern here /#.*/, which means we are telling to the function consider the contents of the sentence and discard the sentence start with #.
Code:
card = "The debit card number is 2222-8880-8989-6789 #valid for 3 days only"
# Delete Ruby-style comments
card = card.sub!(/#.*$/, "")
puts "#{card}"
Output:
Example #4
Operators used for this example is,
- match(method): This method is used for matching the string.
- [^aeiou\W](expression): In this expression we are using operator ^ which specify the start of the letter should be from the letter given. And \W this is used for checking if the string starts with any numeric value.
In the below example we are trying to find if the given name starts with a vowel or not. We are returning true if it is not starting with a vowel and false if it is starting with a vowel. We can explain the below code in the following steps,
First we have defined a function with the name not_start_with_vowel and this function is taking a string as it’s a parameter. This string is the names that are coming from the call to check if they start with a vowel or not. Here we are using the match method of Ruby to check if the given string starts with a vowel or not. We have used the pattern /^aeiou/W, here ^ indicates for the first letter, and \W we have used to check if the given string starts with any numeric characters. Finally we have if and else block so if the first letter is a vowel it will return false as it will match with nil. In the else block if it is not nil which means start does not start with a vowel it will return the true.
Code:
def not_start_with_vowel(string)
if /^[^aeiou\W]/i.match(string) == nil
return false
else
return true
end
end
puts "The name ranjan does not start with vowel is #{not_start_with_vowel("ranjan")}"
puts "The name ranjan does not start with vowel is #{not_start_with_vowel("ajay")}"
Output:
Conclusion
From this tutorial we learned about the Regular Expression of the Ruby and we learned it’ uses in the real world, we saw many examples in these tutorials which will be useful at any instances to filtering or validating any given string or the set of the strings.
Recommended Articles
We hope that this EDUCBA information on “Regular Expression in Ruby” was beneficial to you. You can view EDUCBA’s recommended articles for more information.