DEV Community

Cover image for Regexes with multiple slashes in Ruby
Joe Masilotti
Joe Masilotti

Posted on • Originally published at masilotti.com

2 1

Regexes with multiple slashes in Ruby

I picked up a new tip yesterday while working with regexes in Ruby.

tl;dr - Use %r{} over /.../ when matching regexes with more than one /.

I was testing if a string begins with http:// or https:// and wrote a small regex.

/^https?:\/\//
Enter fullscreen mode Exit fullscreen mode

Broken down, this ensures the string:

  1. Starts with http
  2. The next character is optionally s
  3. The next characters are ://

Even for such a simple regex that feels a bit hard for me to read. There are too many escaped slashes for my taste.

To improve this a bit you can use r%{} over /.../. The syntax works the same but you don’t need to escape slashes.

The regex becomes something much more readable:

%r{^https?://}
Enter fullscreen mode Exit fullscreen mode

GitHub's RuboCop styleguide has a recommendation on when to use this syntax.

Use %r only for regular expressions matching more than one ‘/‘ character. - RubuCop Ruby Style Guide

P.S. I could have probably just used two #starts_with? calls but where’s the fun in that?

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
bizzibody profile image
Ian bradbury

Awesome. I did not know this. Thanks.

Collapse
 
joemasilotti profile image
Joe Masilotti

Glad to hear it, Ian!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay