DEV Community

Cover image for Ruby Regular Expressions
Shaher Shamroukh
Shaher Shamroukh

Posted on

Ruby Regular Expressions

What is Ruby regular expressions (ruby regex)?

Regular expressions appear in many programming languages, with minor differences.

Their purpose is to specify character patterns that subsequently are determined to match or not match.
Pattern matching, in turn, serves as the basis for operations like parsing log files, testing keyboard input for validity, etc.

Regular expressions have a reputation of being incredibly powerful.

Regular expressions are instances of the Regexp class.
and it's literal constructor is a pair of forward slashes:
//

//.class
=> Regexp 
Enter fullscreen mode Exit fullscreen mode

Between the slashes we add the specifics of the regexp.
Now Any pattern-matching operation has two ends: a regexp and a string.
and the simplest way to do that with the match method.
we can do this either way since regular-expression
objects and string objects both respond to match.
Ruby also provides pattern-matching operator,
=~(equal sign and tilde).

p "Match!" if /ruby/.match("ruby is wonderful")
=> "Match!"

p "Match!" if "ruby is wonderful"=~(/ruby/)
=> "Match!" 
Enter fullscreen mode Exit fullscreen mode

Building regular expression pattern

When we write a regexp, we put the definition of the pattern between the forward slashes //.
and what we are putting simply a set of predictions that we want to look for in a string.

regex components

Literal characters,/r/ “match this character”.
The dot wildcard character (.), “match any character”.
Character classes, [aeiou] matches any vowel.

So far, we’ve looked at basic match operations which are true/false tests.

regex.match(string)
string.match(regex)
Enter fullscreen mode Exit fullscreen mode

Till now we got the basics of regexp, and for everyone
I definitely recommend trying out Rubular to build your own regexp taking advantage of it's quick reference, which is awesome for practice, and it is very interactive.

Alt Text

I hope you enjoyed reading the topic as much as i enjoyed writing it. 🙂

Top comments (0)