Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Ruby regex over multiple lines

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?

like image 569
Chowlett Avatar asked Sep 21 '10 16:09

Chowlett


1 Answers

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

like image 137
mthorley Avatar answered Sep 20 '22 14:09

mthorley