https://cs.lmu.edu/~ray/notes/regex/

For each module a student completes at Flatiron School in Chicago, they are required to produce one blog post. In keeping with this, I recently published an article on various generators you can use in Rails. However, shortly thereafter I began completing challenges on the site CodeWars (thanks Ramazan for the suggestion) and, after each completed challenge, I’d read through a few solutions that other people came up with. A lot of these solutions used something called a “Regex”. I had no idea what they were, so… I started Googling.

It turns out that Regex (sometimes referred to as “regular expressions”) are kind of like lines of code that can be used to compare to strings. The main uses for a Regex is to

Basically, it’s all about strings.

Photo by Caio Silva on Unsplash

So, I started learning about this stuff, uh… this morning. So I’m still definitely learning. But a really useful site to look at is Rex Egg. It includes a basic rundown of what you can use, what it returns, and how to make it work well (as with a lot of code, there are better and worse ways of doing things).

The first thing to note is how to recognize a Regex. First, you’ll see a bunch of weird symbols. (Just kidding… sort of). But mostly it’s important to know that it’s kept with two back-slashes. For instance:

/((\d{3})(?:\.|-))?(\d{3})(?:\.|-)(\d{4})/

At the beginning and end of this string (because regexes are strings) is a backslash.

This can be use to pull out phone numbers matching this format, like so:

2.6.1 :001 > array = ["kahsd", "1351", "5554327789", "555.432.6745", "555-564-3423","555.213-4331","555.621.43"]
=> ["kahsd", "1351", "5554327789", "555.432.6745", "555-564-3423", "555.213-4331", "555.621.43"]
2.6.1 :002 > array.select{|item| item =~ /((\d{3})(?:\.|-))?(\d{3})(?:\.|-)(\d{4})/}
=> ["555.432.6745", "555-564-3423", "555.213-4331"]

The sign “=~” is used to mean “match”. So, using typical select iteration, we are going over each item in the array to see if it’s string matches the format listed in the regex and putting only those matches into a return array.

There are tons of resources online to find out how you can uses regexes. A table I found particularly helpful to just get an idea for what you could do was:

https://cs.lmu.edu/~ray/notes/regex/

As I said, I’m still learning myself, so this is just an introduction to the idea of what these are and how they can be used. I may make a follow up post once I’ve become more proficient with them myself.

Thanks!

Student at FlatIron School learning Software Engineering

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store