Skip to content

Commit b61ac66

Browse files
committed
Add Add Comments To Regex With Free-Spacing as a Ruby til
1 parent 3e28983 commit b61ac66

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1137 TILs and counting..._
13+
_1138 TILs and counting..._
1414

1515
---
1616

@@ -864,6 +864,7 @@ _1137 TILs and counting..._
864864
### Ruby
865865

866866
- [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md)
867+
- [Add Comments To Regex With Free-Spacing](ruby/add-comments-to-regex-with-free-spacing.md)
867868
- [Add Linux As A Bundler Platform](ruby/add-linux-as-a-bundler-platform.md)
868869
- [Are They All True?](ruby/are-they-all-true.md)
869870
- [Assert About An Object's Attributes With RSpec](ruby/assert-about-an-objects-attributes-with-rspec.md)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)