DEV Community

Alana Edwards
Alana Edwards

Posted on

TIL: Today I learned Regular Expressions (Regexp)

So, lately I've been learning the Ruby programming language. As a complete beginner it's important to learn and apply the foundational concepts in order to succeed at programming. Therefore, I've been completing all of my module assignments in order to be best prepared for success as a full stack developer. Today, I was working on the "Character Types" assignment where I was tasked with writing a program that takes a randomly sampled string and outputs the total number of letters, spaces, and digits in the given string.

strings = [
"here 12 plus 25",
"puzzle number 04 ",
" "
]
string = strings.sample
pp string

I used regular expressions (regexp), the .scan method, and the .length method to make that possible.

Regular expressions are a sequence of characters that match a string. They are very useful for extracting information from a string or when you're using the .gsub method to replace information inside of a string.

In this example:

letter_count = string.scan(/[A-za-z]/).length
pp "Number of letters in the string is: #{letter_count}"

space_count = string.scan(/\s/).length
pp "Number of spaces in the string is: #{space_count}"

digit_count = string.scan(/\d/).length
pp "Number of digits in the string is: #{digit_count}"

I wanted to get the letter count, space count, and digit count of the randomly outputted string. So in order to do so, I used the .scan() method to iterate through the strings and regular expression arguments (/[A-za-z]/)
which matches all capital and lowercase letters, (/\s/) which matches all spaces, and (/\d/) which matches all digits.

Top comments (3)

Collapse
 
bibimbop123 profile image
Brian Kim

I also found gsub method and regex incredibly useful in ruby. I found myself asking questions to chatgpt about regex in javascript, and discovered that regex can be used with the following javascript methods (.test, .replace, .split, and .match)

Collapse
 
pimp_my_ruby profile image
Pimp My Ruby

Hi Alana, be careful when dealing with regex :)

There is this quote that said

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

In this way, I suggest you to use rubular.com/ in order to check your regexes :)

Collapse
 
prettyalana profile image
Alana Edwards • Edited

Hi V,

Thank you for your comment! I took your advice and was able to check that all of the regexes worked on the randomly sampled strings.

strings = [
"here 12 plus 25",
"puzzle number 04 ",
" "
]
string = strings.sample

Image description