Ruby

Ruby – useful regular expressions

Ruby – useful regular expressions February 22, 2018Leave a comment

Since ruby regular expressions are present in almost every app, it’s useful to know about few simple expressions that can save some time during the development.

Matching only whole word in given sentence

\b – Matches word boundaries when outside brackets; backspace (0x08) when inside brackets

"The sky is blue".match(/\bis\b/) #=> is
"The sky iss blue".match(/\bis\b/) #=> nil

Getting the position in string where our matching is starting and ending

"The sky is blue".match(/\bis\b/).begin(0) #=> 8 - it points to letter i
"The sky is blue".match(/\bis\b/).end(0) #=> 11 - it points to white space

Matching any number

\d – A digit character ([0-9])

"The sky is blue1".match(/\d/) #=> 1
"The sky iss blue".match(/\d/) #=> nil

Pattern that must be matched in order for a regular expression to be satisfied, but that will not be included in a successful match

"The sky is blue".match(/(?<=The sky is ).*/) #=> blue

Reference to named groups

"The sky is blue".gsub(/(?<=The sky is )(?.*)/, 'very \k') #=> "The sky is very blue"

If you know any other useful regex expressions please share them in the comments section!

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

Leave a Reply

Your email address will not be published. Required fields are marked *