RegExes in Ruby — A Brief Summary
By: James Dorr
Tags: Ruby, Regular Expressions, Regex, Flatiron School, Regexp

More importantly, what are regexes for?

Matching

The methods .match, .scan, and =~ can be used to match a string and a pattern (which is inside a regex). This can be very helpful for things like validation.

We want {4} digits \d followed by -. All of that {3} times, ending with {4} digits \d.

Here, card.match(pattern) also works. If .match does not find a pattern, “nil” is returned.

dash_numbers looks for a dash followed by {4} digits \d

The return value for =~, 4, is the index number where the pattern was first found. That is, the method =~ returns the index where the pattern was first found, or “nil” if not found. dash_numbers =~ card works the same as card =~ dash_numbers.

To get simple true or false answers, we can use .match? and !!(regex =~ string) (or !!(string =~ regex).

.match? is trying to find {16} digits \d in a row, and will just return “true” or “false”

Changing

chamelion.gsub(‘green’, new_color)

The methods .sub and .gsub can replace patterns in strings — .sub replaces the first occurance, and .gsub replaces all occurances. Like some other methods in Ruby, adding ! to the end of .sub! and .gsub! causes them to permanently modify the original strings, as opposed to just returning new strings.

In both lines 3 and 5, we are just trying to match any lower-case vowels

In the examples above, we replaced the first lower-case vowel (.sub) and then all lower-case vowels (.gsub) with “#.”

Regexes can also be used with .split and .scan, but the regex must be in the parentheses and not before the periods, or it will return a “No Method” error.

Assigning Variables!

This is quite exciting

Of course, we can assign variables as usual, like with every method.

.scan returns every chunk of {4} digits \d

However, regexes also allow us to assign variables from within the regex. I’m nerding out right now! This is exciting!

That easily, Ruby scanned the text and withdrew 1 or more (+) digits (\d) in a row, and we can examine that data like we would from an array.

But there’s more! Similar to a hash, we can assign names to the things we’ve matched. For this, we use the syntax /(?<key>regex)/ or /(?’key’regex)/. Ruby refers to these as names within capture groups, but it might be easier to think of them as key/value pairs. Here, “example” is of the MatchData class.

In the example above, regex[:name] will be assigned to the first instance of a capital letter [A-Z] followed by 2 or more word characters \w, and regex[“age”] will be set to the first digit or consecutive digits. Then, we can get data from the MatchData instance “example” like a hash (and like an array, as previously mentioned).

Lastly, we can get some interesting information from the same MatchData using the $.

These combinations with $ can give you the everything before the first match ($`), everything including and between the matches ($&), everything after the last match ($’), the first match ($1), and the second match ($2).

How else can regexes be useful?

Checking email formats

/.+@.+\..+/ matches any character 1 or more times, followed by @, followed by any character 1 or more times, followed by a period, followed by any character 1 or more times

/.+@.+\..+/ matches any character 1 or more times, followed by @, followed by any character 1 or more times, followed by a period, followed by any character 1 or more times Ensuring names are typed correctly

/([A-Z].+){2,}/ matches any capital character followed by 1 or more of any character, and all of that 2 or more times

/([A-Z].+){2,}/ matches any capital character followed by 1 or more of any character, and all of that 2 or more times Checking price data

/\$(?<dollars>\d+)\.(?<cents>\d+)/ first matches any digits after the $ sign and assigns them to [:dollars], and then matches any digits after the period and assigns them to [:cents]

/\$(?<dollars>\d+)\.(?<cents>\d+)/ first matches any digits after the $ sign and assigns them to [:dollars], and then matches any digits after the period and assigns them to [:cents] Making password regulations

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0–9]).{6,12}$/ between the beginning (^) and the end ($), there must be a capital letter, a lower case letter, and a digit. All of these can come in any order (?=), and the whole thing must be 6 to 12 characters long

/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0–9]).{6,12}$/ between the beginning (^) and the end ($), there must be a capital letter, a lower case letter, and a digit. All of these can come in any order (?=), and the whole thing must be 6 to 12 characters long Searching in Atom and other text editors

i*’*m* — with “case insensitive” on, Atom would find any instance of 0-∞ i or I, 0-∞ ‘, and 0-∞ m or M. Keep in mind, this would also pick up any words with i, I, ‘, m, or M in them, but it would at least help you find a very badly mistyped “I’m.”

Actually, we can put this “case insensitivity” into our regexes outside of Atom, as well. Options come after the regex’s closing and modify it. The most common ones are

/Ruby/i

ignores case, so ruby, Ruby, and RuBy all match.

ignores case, so ruby, Ruby, and RuBy all match. /Ruby/x

ignores whitespace (\s)

ignores whitespace (\s) /Ruby/m

matches multiple lines, and [enter] is just a character (

)

There are tons of cool things you can do with regexes — like even checking that all of the letters in a string are from the Latin alphabet (/^\p{Latin}+$/). There are so many things you can do that many books have been written solely dedicated to regular expressions. Hopefully this short summary has helped us become comfortable enough with the idea to understand some common regex patterns in code.

What can regexes help you do?