LoginSignup
10
6

More than 5 years have passed since last update.

RuboCop | Style/RegexpLiteral

Posted at

RuboCop | Style/RegexpLiteral

概要

RuboCopの「Style/RegexpLiteral」警告について。

正規表現に任意の数のスラッシュが含まれる場合に、

/reg\/\/exp/

の記法を使わずに、

%r{reg//exp}

を利用するように警告を出す。
逆に、スラッシュが任意の数になっていないにも関わらず
%r 記法を利用していると警告をうけます。
デフォルトはスラッシュを2個以上使っていると警告を出す。

bundlerでgemのテンプレートを作っている場合

bundlerでgemのテンプレートを作っている場合, bundlerが生成する gemspec の中で

  spec.executables   = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
  spec.test_files    = spec.files.grep(%r{^(test|spec|features)/})

のように、スラッシュ1個の正規表現に対して %r 記法を利用しているため
RuboCop警告を受けることになってしまいます。

RegexpLiteral

各設定値での検証結果をまとめます。

検証プログラム

raise_args
hoge = 'hoge'
print hoge =~ /hoge/
print hoge =~ /ho\/ge/
print hoge =~ /ho\/\/ge/
print hoge =~ %r{hoge}
print hoge =~ %r{ho/ge}
print hoge =~ %r{ho//ge}

実行結果 デフォルト の場合

.rubocop.yml
RegexpLiteral:
  MaxSlashes: 1
$rubocop regexp_literal.rb
Inspecting 1 file
C

Offenses:

regexp_literal.rb:4:15: C: Use %r for regular expressions matching more than 1 '/' character.
print hoge =~ /ho\/\/ge/
              ^^^^^^^^^^
regexp_literal.rb:5:15: C: Use %r only for regular expressions matching more than 1 '/' character.
print hoge =~ %r{hoge}
              ^^^^^^^^
regexp_literal.rb:6:15: C: Use %r only for regular expressions matching more than 1 '/' character.
print hoge =~ %r{ho/ge}
              ^^^^^^^^^

1 file inspected, 3 offenses detected

実行結果 compact を設定にします

.rubocop.yml
RegexpLiteral:
  MaxSlashes: 0
$rubocop regexp_literal.rb
Inspecting 1 file
C

Offenses:

regexp_literal.rb:3:15: C: Use %r for regular expressions matching more than 0 '/' characters.
print hoge =~ /ho\/ge/
              ^^^^^^^^
regexp_literal.rb:4:15: C: Use %r for regular expressions matching more than 0 '/' characters.
print hoge =~ /ho\/\/ge/
              ^^^^^^^^^^
regexp_literal.rb:5:15: C: Use %r only for regular expressions matching more than 0 '/' characters.
print hoge =~ %r{hoge}
              ^^^^^^^^

1 file inspected, 3 offenses detected

RuboCopまとめ記事

10
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6