As far as I'm aware, to create a regexp with flags in Ruby, we have two options:
/ delimiter: /test/mUsing 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.
Rubocop should not produce a warning
Rubocop produces warning
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
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)
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}mdoesn'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".
Most helpful comment
those are both valid syntax, they match different strings