From b61ac66ffe68d1cfebf8987ce8e6c75f8613db40 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 8 Jul 2021 16:37:27 -0500 Subject: [PATCH] Add Add Comments To Regex With Free-Spacing as a Ruby til --- README.md | 3 +- ...add-comments-to-regex-with-free-spacing.md | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 ruby/add-comments-to-regex-with-free-spacing.md diff --git a/README.md b/README.md index f76540d..93310e2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1137 TILs and counting..._ +_1138 TILs and counting..._ --- @@ -864,6 +864,7 @@ _1137 TILs and counting..._ ### Ruby - [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md) +- [Add Comments To Regex With Free-Spacing](ruby/add-comments-to-regex-with-free-spacing.md) - [Add Linux As A Bundler Platform](ruby/add-linux-as-a-bundler-platform.md) - [Are They All True?](ruby/are-they-all-true.md) - [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md) diff --git a/ruby/add-comments-to-regex-with-free-spacing.md b/ruby/add-comments-to-regex-with-free-spacing.md new file mode 100644 index 0000000..bd3f3ed --- /dev/null +++ b/ruby/add-comments-to-regex-with-free-spacing.md @@ -0,0 +1,50 @@ +# Add Comments To Regex With Free-Spacing + +Ruby's regex syntax supports a [Free-Spacing +mode](https://ruby-doc.org/core-3.0.1/Regexp.html#class-Regexp-label-Free-Spacing+Mode+and+Comments). +When this mode is enabled, all the literal whitespace in the regular expression +is ignored and comments can be included at the end of lines. This is enabled by +appending the `x` option at the end of the regex. + +Here is a regex with Free-Spacing mode enabled (see the `x` at the end). + +```ruby +simple_email = /\A.+@.+\z/x +``` + +Though it's enabled, it is not really being used. + +Here is the same regular expression, but this time I've spaced it out and added +comment annotation to make the regex easier to understand. + +```ruby +simple_email = / + \A # beginning of the string + .+ # any opening characters + @ # the email's `@` symbol + .+ # the rest of the email + \z # the end of the string +/x +``` + +To be sure the extra space and comments aren't messing things up, here is some +code to test it out. + +```ruby +test_emails = [ + 'taco', + 'email@example.com', + 'more.complex+email@example.com', + '@' +] + +test_emails.each do |email| + if (simple_email =~ email) == 0 + puts "#{email} looks like an email" + else + puts "#{email} may not be an email" + end +end +``` + +[source](https://twitter.com/jasonrudolph/status/1413240725064519681?s=20)