Tuesday 12 June 2012

Ruby: regex

The Ruby operator =~ matches a string against a pattern. It returns character offset into the string at which the match occurred, or returns nil if match fails. Your can put the regex first or the string first. Either way is ok. Because nit is equivalent to false in a boolean context, you can use the result as a condition in if or while statements.

Regular expression also defines === as a simple pattern match:
case line
when /title=(.*)/
  puts "Title is #$1"
when /track=(.*)/
puts "Track is #$1"
when /artist=(.*)/
puts "Artist is #$1"
end

Regular expression options

  • i Case insensitive.
  • o Substitute once. Any #{...} substitutions in a particular regular expression literal will be performed just once, the first time it is evaluated. Otherwise, the substitutions will be performed every time the literal generates a Regex object.
  • m Multiline mode. Normally, "." matches any character except a newline. With the /m option, "." matches any character.
  • x Extended mode. Complex regular expression can be difficult to read. The x option allows you to insert spaces and newlines in the pattern to make it more readable. You can also use # to introduce comments.
Reference: Programming in Ruby 1.9: The Pragmatic Programmer's Guide

No comments :

Post a Comment