Mohammed Aslam about subscribe

Ruby’s Regular Expressions

Regular expressions in simple terms is a pattern that can be matched against a string. With regular expression you can test a string to check if it matches a pattern, or you can change the entire string replacing its certain parts that matches a pattern or you can also extract from a string the section that matches a pattern.

In Ruby we write regular expression literal in between forward slashes. For example, /ruby/ is a regular expression literal.
so /ruby/ matches “i love ruby language” string. To match a special character, we have to precede it with a backslash. So /\// is a pattern that matches forward slash.

Ruby uses =~ to match a pattern with a string. This returns the offset of the character at which the match occurred.
For example,

/ruby/ =~ "i love ruby language" => 7
/matz/ =~ "matz is an awesome person" => 0

When the pattern matching fails, it will return a nil.

For a detailed explanation on Ruby’s regular expression, I would recommend Programming Ruby 1.9

Related Posts

3 Comments

Leave a Reply

Latest Tweet

"Yaaaay . My Lenovo back to working condition. Thanks to Lenovo International warranty service :)"