Useful regular expressions

Ruby

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

The 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"