Ruby: String representations of regular expressions

Posted . Visible to the public.

Ruby's regular expressions can be represented differently.
When serializing them, you probably want to use inspect instead of to_s.

For the examples below, consider the following Regexp object.

regexp = /^f(o+)!/mi


Using to_s will use a format that is correct but often hard to read Show snapshot .

>> regexp.to_s
=> "(?mi-x:^f(o+)!)"


As the Ruby docs say Show snapshot :

Perhaps surprisingly, #inspect actually produces the more natural version of the string than #to_s.

>> regexp.inspect
=> "/^f(o+)!/mi"

source and options

You can use source to see an expression's pattern, and options for its switches.

>> regexp.source
=> "^f(o+)!"
>> regexp.options
=> 5

Note that options returns a bitmask. If necessary, you could compare that to Regexp's switch constants:

>> regexp.options & Regexp::IGNORECASE                  
=> 1
>> regexp.options & Regexp::EXTENDED
=> 0
>> regexp.options & Regexp::MULTILINE
=> 4
Arne Hartherz
Last edit
Arne Hartherz
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2017-01-03 15:43)