Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Ruby regex doesn't fit on line

When I have a very long regex, like a cucumber step definition, what would be the best way to line wrap it?

example, i would like something like:

When /^I have a very long step definition here in my step definition file$/ do
  ...
end

break up into two lines (this doesnt work:)

When /^I have a very long step definition here in /\
    /my step definition file$/ do
  ...
end

2018 update

If you're here specifically for cucumber, using cucumber expressions is a great alternative to regexes

like image 699
Len Avatar asked Jul 10 '13 08:07

Len


1 Answers

You can use a verbose regex with the /x modifier, but then you need to make spaces explicit because they will otherwise be ignored. Another advantage is that this allows you to comment your regex (which, if it's long, might be a good idea):

/^                               # Match start of string
I[ ]have[ ]a[ ]very[ ]long[ ]
step[ ]definition[ ]here[ ]
in[ ]my[ ]step[ ]definition[ ]file
$                               # Match end of string
/x
like image 181
Tim Pietzcker Avatar answered Oct 20 '22 04:10

Tim Pietzcker