Using Regular Expressions with Ruby
Author: ceefour | Filed under: Ajax, Rails, Ruby, ToolsRuby is a high level, object-oriented open source scripting language. It has excellent support for regular expressions as a language feature.
In Ruby, a regular expression is written in the form of /pattern/modifiers where “pattern” is the regular expression itself, and “modifiers” are a series of characters indicating various options. The “modifiers” part is optional. This syntax is borrowed from Perl.
Ruby supports the following modifiers:
- /i makes the regex match case insensitive.
- /m makes the dot match newlines. Ruby indeed uses /m, whereas Perl and many other programming languages use /s for “dot matches newlines”.
- /x tells Ruby to ignore whitespace between regex tokens.
- /o causes any #{…} substitutions in a particular regex literal to be performed just once, the first time it is evaluated. Otherwise, the substitutions will be performed every time the literal generates a Regexp object.
You can combine multiple modifiers by stringing them together as in /regex/is.
In Ruby, the caret and dollar always match before and after newlines. Ruby does not have a modifier to change this. Use \A and \Z to match at the start or the end of the string.
Since forward slashes delimit the regular expression, any forward slashes that appear in the regex need to be escaped. E.g. the regex 1/2 is written as /1\/2/ in Ruby.
Read more on: Regular-Expressions.info home page.
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.