Regex and Range in Ruby language
Regex stands for ‘regular expressions.’ A regular expression represents a string of characters that defines a search pattern. It allows us to find specific ways inside a string. Validation and parsing are two applications of ruby Regex. Between two forward slashes, Ruby Regex expressions are declared. In contrast, the values between two endpoints are represented by a range. Without having to type them all out, we may utilize ranges to match numerous letters or numbers.
Example:
# search for the word ‘my’
“Welcome, to my channel!” =~ /my/
If the word was found (successful match), this provides the index of the first occurrence; otherwise nil. We could use the String#include? Function if we don't care about the index.
The match method is another technique to see if a string matches a Regex:
Example:
# Ruby program of Regex
# check whether the word is present in the string or not
if “Welcome, to my channel!”.match(/my/)
puts “match found.”
end
You can also try this code with Online Ruby Compiler
Run Code
Methods in Ruby that can be used with Regex
.scan() - Look for all the Regex matches in a string. Returns an array of data that has been matched. It's vital to remember that even if there's just one match, the array will still have one element.
.match() - If a match is detected, the method produces a MatchData object; otherwise, it returns nil. The MatchData object comes out to be true in a boolean context. The MatchData object evaluates the text that was matched in a string context.
.sub() and .gsub() - Substitute a different string for the matched string, supplied as a second parameter. The sole difference between .sub() and .gsub() is that the former substitutes the first match it encounters, while the latter does it globally (for each detected match).
.split() - Left and right of the Regex match, split the string.
Types of regular expression
Character ranges can be specified using a variety of short expressions. They can be broadly divided into positive and negative forms.
Positive form for specifying character ranges:
- \d is equivalent to [0-9]
- \w is the same as [0-9a-zA-Z_]
- \s represents white space
Negative form for specifying character ranges:
- \D is anything but a number
- \W is everything except [0-9a-zA-Z_]
- \S is anything but a space
The dot character (.) matches everything except new lines. If you wish to look for the . character, you must first escape it.
Modifiers for regular expression
We can use modifiers to match several characters:
- +: used for representing 1 or more characters
- ?: used for only 0 and 1 character
- *: used for representing 0 or more characters
- i: used for ignoring case while matching a text
- m: used for matching multiple lines as well as recognizing new lines as standard characters
- x: used for ignoring whitespace and allowing comments in normal expressions
- {x,y}: used for the number of characters between x and y
What Is The Regex Object And How to use it?
The command /regex/ generates a new object of the Regex class. You can save it as a variable and use it again and again, or you can use the literal Regex directly. Ruby has various methods for determining whether a Regex match (part of) a string.
Regex object can be created in two ways:
- A literal notation: In this method, parameters are separated by slashes and are not included in quotation marks.
- A constructor: This method slashes separate parameters that are not enclosed in quotation marks.
Regular expression objects can be created by using the following three ways:
// literal notation
let reg = /pq+r/i;
// constructor having first argument as string pattern
let reg = new RegExp(‘pq+r’, ‘i’)
// constructor having the first argument as a regular expression literal
let reg = new RegExp(/pq+r/, ‘i’)
Frequently Asked Questions
What kinds of things can Ruby be used for?
Ruby is a multi-purpose programming language that may be used for various tasks. Ruby is an excellent language for creating static webpages, desktop programs, data processing services, and even automation solutions. It's used for web servers, DevOps, web scraping, and crawling, among other things.
Why should you learn the Ruby programming language?
Ruby is a programming language intended to increase programmer efficiency while still being enjoyable. Ruby is popular among programmers because it is high-level and has a straightforward syntax. You have less code to write and can focus on finding a solution to your problem.
What is the difference between Ruby and Python?
Ruby is a procedural language that may be disguised as an OO language. There are no functions and only the method calls while python is a cross-platform programming language. It has procedural programming functions as well as object-oriented programming objects.
What is the result of a regex match?
Match(String) returns the first substring in an input string that matches a regular expression pattern.
What is the definition of a regex pattern?
Regex (Regular Expression) is a pattern (or filter) that describes a set of strings that match the pattern.
Conclusion
Regular expressions are fantastic, but they can be a little challenging at times. You can design your ruby Regex more dynamically by using a tool like rubular.com. It's now your turn to fire up that editor and get coding!
You can also refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Ruby-related topics such as 8 reasons why Ruby should be your first language, everything you wished you knew about Ruby on Rails, Ruby on Rails for your next web development project, career opportunities after mastering Ruby on Rails, Ruby vs. Python, and many more!
Do upvote our blog to help our other ninjas to grow!
Happy reading!!