Read more

Ruby: String representations of regular expressions

Arne Hartherz
January 03, 2017Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

For the examples below, consider the following Regexp object.

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

to_s

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

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

inspect

As the Ruby docs say Show archive.org 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
Posted by Arne Hartherz to makandra dev (2017-01-03 16:43)