WB
Home About Work Notes

Intro to Ruby Regular Expressions

  12th May 2015
  1 minute
  Ruby

Regular Expressions are used to match patterns to strings. They are super powerful and very scary. If you use them badly your code can become totally un-maintainbale and confusing. When the time is right and used wisely they are great.

Be careful not to use regular expressions to create more problems than you started with.

Regular Expressions in your Rubies

# create an Regexp with forward slashes:
/hey/

# check for matches using the operator,
# returning the index of the first match,
# or nil if no matches
/hey/ =~ 'Oi! hey you'
=> 4

# use .match to return a MatchData Object of the first match
/hey/.match('hey you')
=> #<MatchData "hey">

# use scan to return an array of matches
text = "426 792 327 123"
pattern = /\d+/
text.scan(pattern)
=> ["426", "792", "327", "123"]

A MatchData object encapsulates all the results of a pattern match.

Trying Regular Expressions Out

So you have an expression you are writing. How do you test it out.

Rubular

Rubular

Reference

ruby-doc.org/core-2.1.1/Regexp.html

Lets make something together!

Get in touch at [email protected]


Copyright 2024 © All rights Reserved.
Crafted Web Development. Built With