10

当我有一个很长的正则表达式时,比如黄瓜步骤定义,换行的最佳方法是什么?

例如,我想要类似的东西:

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

分成两行(这不起作用:)

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

2018 年更新

如果您是专门为黄瓜而来的,那么使用黄瓜表达式是正则表达式的绝佳替代品

4

4 回答 4

14

您可以使用带有修饰符的详细正则表达式/x,但是您需要明确空格,否则它们将被忽略。另一个优点是这允许您评论您的正则表达式(如果它很长,可能是一个好主意):

/^                               # Match start of string
I[ ]have[ ]a[ ]very[ ]long[ ]
step[ ]definition[ ]here[ ]
in[ ]my[ ]step[ ]definition[ ]file
$                               # Match end of string
/x
于 2013-07-10T08:31:08.387 回答
1

字符串到正则表达式的转换呢?你会失去语法突出显示,但我会说这还不错?

When( Regexp.new(
  '^My long? regex(?:es) that are '\
  '(?:maybe ) broken into (\d+) lines '\
  'because they (?:might )be non-readable otherwise$'
)) do |lines|
  ...
end
# => /^My long? regex(?:es) that are (?:maybe ) broken into (\d+) lines because they (?:might )be non-readable otherwise$/
于 2016-11-19T17:00:16.830 回答
0

关于什么

/a\
b/
# => /ab/
于 2013-07-10T08:31:52.390 回答
-2

I know you want it in Ruby, but i can give you an example how it can be realised in Perl. I really think that you can use the idea behind this in Ruby as well.

my $re1 = "I have a very long step definition here in";
my $re2 = "my step definition file";

if ( $line =~ m/^$re1 $re2$/i ) {
    ...
}

The idea is to save the Regex into a variable and write the variable inside the regex.

于 2013-07-10T09:00:00.953 回答