Split Ruby regex into multiple lines

This is not exactly what you expect! I do not want the regular expression to match a line break; instead, I want to write a long regular expression that I would like to split into several lines of code for readability.

Something like:

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

Can this be done?

+59
code-formatting ruby regex
Sep 21 '10 at 16:03
source share
3 answers

You need to use the /x modifier, which turns on the free space mode .

In your case:

 "bar" =~ /(foo| bar)/x 
+42
Sep 21 '10 at 16:16
source share

Using% r with the x parameter is the preferred way to do this.

Check out 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

+103
Dec 11 '13 at 16:39
source share

you can use:

 "bar" =~ /(?x)foo| bar/ 
+3
Dec 11 '13 at 16:28
source share



All Articles