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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)