|
| 1 | +# Add Comments To Regex With Free-Spacing |
| 2 | + |
| 3 | +Ruby's regex syntax supports a [Free-Spacing |
| 4 | +mode](https://ruby-doc.org/core-3.0.1/Regexp.html#class-Regexp-label-Free-Spacing+Mode+and+Comments). |
| 5 | +When this mode is enabled, all the literal whitespace in the regular expression |
| 6 | +is ignored and comments can be included at the end of lines. This is enabled by |
| 7 | +appending the `x` option at the end of the regex. |
| 8 | + |
| 9 | +Here is a regex with Free-Spacing mode enabled (see the `x` at the end). |
| 10 | + |
| 11 | +```ruby |
| 12 | +simple_email = /\A.+@.+\z/x |
| 13 | +``` |
| 14 | + |
| 15 | +Though it's enabled, it is not really being used. |
| 16 | + |
| 17 | +Here is the same regular expression, but this time I've spaced it out and added |
| 18 | +comment annotation to make the regex easier to understand. |
| 19 | + |
| 20 | +```ruby |
| 21 | +simple_email = / |
| 22 | + \A # beginning of the string |
| 23 | + .+ # any opening characters |
| 24 | + @ # the email's `@` symbol |
| 25 | + .+ # the rest of the email |
| 26 | + \z # the end of the string |
| 27 | +/x |
| 28 | +``` |
| 29 | + |
| 30 | +To be sure the extra space and comments aren't messing things up, here is some |
| 31 | +code to test it out. |
| 32 | + |
| 33 | +```ruby |
| 34 | +test_emails = [ |
| 35 | + 'taco', |
| 36 | + 'email@example.com', |
| 37 | + 'more.complex+email@example.com', |
| 38 | + '@' |
| 39 | +] |
| 40 | + |
| 41 | +test_emails.each do |email| |
| 42 | + if (simple_email =~ email) == 0 |
| 43 | + puts "#{email} looks like an email" |
| 44 | + else |
| 45 | + puts "#{email} may not be an email" |
| 46 | + end |
| 47 | +end |
| 48 | +``` |
| 49 | + |
| 50 | +[source](https://twitter.com/jasonrudolph/status/1413240725064519681?s=20) |
0 commit comments