Intro to Ruby Regular Expressions

 May 2015

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:

# 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+/
=> ["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.




Web Development

Got a web project you need doing well? We can help with that!

Find out more