Split Ruby regex over multiple lines

RubyRegexCode Formatting

Ruby Problem Overview


This might not be quite the question you're expecting! I don't want a regex that will match over line-breaks; instead, I want to write a long regex that, for readability, I'd like to split onto multiple lines of code.

Something like:

"bar" =~ /(foo|
           bar)/  # Doesn't work!
# => nil. Would like => 0

Can it be done?

Ruby Solutions


Solution 1 - Ruby

Using %r with the x option is the prefered way to do this.

See this example from the github ruby style guide

regexp = %r{
  start         # some text
  \s            # white space char
  (group)       # first group
  (?:alt1|alt2) # some alternation
  end
}x

regexp.match? "start groupalt2end"

https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md#regular-expressions

Solution 2 - Ruby

You need to use the /x modifier, which enables free-spacing mode.

In your case:

"bar" =~ /(foo|
           bar)/x

Solution 3 - Ruby

you can use:

"bar" =~ /(?x)foo|
         bar/

Solution 4 - Ruby

Rather than cutting the regex mid-expression, I suggest breaking it into parts:

full_rgx = /This is a message\. A phone number: \d{10}\. A timestamp: \d*?/

msg = /This is a message\./
phone = /A phone number: \d{10}\./
tstamp = /A timestamp: \d*?/

/#{msg} #{phone} #{tstamp}/

I do the same for long strings.

Solution 5 - Ruby

regexp = %r{/^ 
            WRITE 
            EXPRESSION 
            HERE 
          $/}x

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChowlettView Question on Stackoverflow
Solution 1 - RubymthorleyView Answer on Stackoverflow
Solution 2 - RubySilentGhostView Answer on Stackoverflow
Solution 3 - RubyMontellsView Answer on Stackoverflow
Solution 4 - RubyKacheView Answer on Stackoverflow
Solution 5 - RubyN Djel OkoyeView Answer on Stackoverflow