An Interest In:
Web News this Week
- April 3, 2024
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
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?:\/\//
Broken down, this ensures the string:
- Starts with
http
- The next character is optionally
s
- 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 dont need to escape slashes.
The regex becomes something much more readable:
%r{^https?://}
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 wheres the fun in that?
Original Link: https://dev.to/joemasilotti/regexes-with-multiple-slashes-in-ruby-1c4p
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To