Rubocop: Regexp with flags: "Use %r around regular expression."

Created on 17 Feb 2017  路  5Comments  路  Source: rubocop-hq/rubocop

As far as I'm aware, to create a regexp with flags in Ruby, we have two options:

  1. Use the literal syntax with a / delimiter: /test/m
  2. Instantiate a RegExp object: RegExp.new('test', REGEXP::MULTILINE))

Using the / delimiter is frowned upon when creating regexps that contain slashes, and Rubocop generates an error appropriately. However, the alternative can be long-winded and ugly. So you can consider this issue debatable: we could just instantiate a RegExp object to get around the warning, or we could allow slash delimiters when using flags.


Expected behavior

Rubocop should not produce a warning

Actual behavior

Rubocop produces warning

Steps to reproduce the problem

Write a Regexp that includes slashes and uses flags:

_regexp = /\/hello/m

Run rubocop against the file:

~ <$> rubocop ruby.rb
Inspecting 1 file
C

Offenses:

ruby.rb:1:1: C: Missing frozen string literal comment.
_regex = /\/test/m
^
ruby.rb:1:10: C: Use %r around regular expression.
_regex = /\/test/m
         ^^^^^^^^^

1 file inspected, 2 offenses detected

RuboCop version

Include the output of rubocop -V. Here's an example:

0.47.1 (using Parser 2.4.0.0, running on ruby 2.3.1 x86_64-darwin16)

Most helpful comment

those are both valid syntax, they match different strings

'this string has a /regex/ in it'.match? %r{/regex/} #=> true
'this one has no slashes: regex '.match? %r{/regex/} #=> false

'this string has a /regex/ in it'.match? %r{regex} #=> true
'this one has no slashes: regex '.match? %r{regex} #=> true

All 5 comments

As far as I'm aware, to create a regexp with flags in Ruby, we have two options:

Are you sure %r{/test}m doesn't work?

I can't believe I didn't try that. OK, never mind!

Are you sure %r{/test}m doesn't work?

If you (like me) found this post many years later and tried to use %r{/regex/} - it does not work. Proper syntax is %r{regex} without slashes.

those are both valid syntax, they match different strings

'this string has a /regex/ in it'.match? %r{/regex/} #=> true
'this one has no slashes: regex '.match? %r{/regex/} #=> false

'this string has a /regex/ in it'.match? %r{regex} #=> true
'this one has no slashes: regex '.match? %r{regex} #=> true

those are both valid syntax, they match different strings

I completely agree that %r{/needle/} is a valid syntax. However usually by %r{ne{2}dle} we would be looking for a substring "needle" in "a needle in a haystack" and not "/needle/" as in "we would need scissors/needle/thread".

Was this page helpful?
0 / 5 - 0 ratings

Related issues

deivid-rodriguez picture deivid-rodriguez  路  3Comments

AndreiMotinga picture AndreiMotinga  路  3Comments

millisami picture millisami  路  3Comments

kirrmann picture kirrmann  路  3Comments

herwinw picture herwinw  路  3Comments