Skip to content

Commit 1849bc4

Browse files
committed
Added regular_expressions/heregexes
Removed heregexes from wanted recipes
1 parent 8a89b59 commit 1849bc4

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
layout: recipe
3+
title: Using Heregexes
4+
chapter: Regular Expressions
5+
---
6+
7+
h2. Problem
8+
9+
You need to write a complex regular expression.
10+
11+
h2. Solution
12+
13+
Use Coffeescript's "heregexes" -- extended regular expressions that ignore internal whitespace and can contain comments.
14+
15+
{% highlight coffeescript %}
16+
pattern = ///
17+
^\(?(\d{3})\)? # Capture area code, ignore optional parens
18+
[-\s]?(\d{3}) # Capture prefix, ignore optional dash or space
19+
-?(\d{4}) # Capture line-number, ignore optional dash
20+
///
21+
[area_code, prefix, line] = "(555)123-4567".match(pattern)[1..3]
22+
# => ['555', '123', '4567']
23+
{% endhighlight %}
24+
25+
h2. Discussion
26+
27+
Breaking up your complex regular expressions and commenting key sections makes them a lot more decipherable and maintainable. For example, changing this regex to allow an optional space between the prefix and line number would now be fairly obvious.

wanted-recipes.textile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@ h2. Regular Expressions
113113
* Searching for substrings # "foo bar baz".match(/ba./) # => [ 'bar', index: 4, input: 'foo bar baz' ]
114114
* Searching for substrings # "foo bar baz".search(/ba./) # => 4
115115
* Replacing substrings # "foo bar baz".replace( /ba./, 'foo') # => "foo foo baz"
116-
* Extended "heregexes"
117116

118117
h2. AJAX
119118

0 commit comments

Comments
 (0)