当我已经在使用 %r 时,为什么 rubocop 要求我将 // 放在正则表达式周围?

Why is rubocop asking me to put // around regex when i'm using %r already?

我有以下正则表达式

  regexp = %r{
     ((returned|undelivered)\smail|mail\sdelivery(\sfailed)?)
  }x

但是当我在上面 运行 rubocop 时,它抱怨说我需要 "Use // around regular expression."

我该如何解决?

我不 运行 rubocop 所以不确定这是否能解决您的问题。使用 %r:

时,您可以使用 // 而不是 {} 来包围正则表达式
regexp = %r/((returned|undelivered)\smail|mail\sdelivery(\sfailed)?)/x

when I run rubocop on it, it complains that I need to "Use // around regular expression."

How can I get around it?

我认为消息很清楚:要绕过它,您可以在正则表达式周围使用 //

regexp = /((returned|undelivered)\smail|mail\sdelivery(\sfailed)?)/x

您可以通过将 .rubocop.yml 文件添加到项目文件夹的根目录并设置适当的配置来禁用(和启用)任何 rubocop cop。要查看您可以做什么,请查看 rubocop 包中的全局 default.yml。评论满了。

对于这个特殊问题,创建一个 .rubocop.yml 和...

要完全禁用警察:

Style/RegexpLiteral: Enabled: false

始终 使用%r:

Style/RegexpLiteral: EnforcedStyle: percent_r

您可以在 /.../x 中使用多行正则表达式:

regexp = /
  ((returned|undelivered)
  \s
  mail|mail
  \s
  delivery
  (\sfailed)?)
/x

Rubocop gem doc

中查看更多内容