Skip to content

Commit 4e3c08a

Browse files
committed
added more detail to regex match all, and problem clarified
1 parent 2e47789 commit 4e3c08a

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

chapters/regular_expressions/finding-all-matches.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ chapter: Regular Expressions
77

88
You need to find all matches, not just the first.
99

10+
For example,
11+
12+
{% highlight coffeescript %}
13+
/\d+/g.exec "I have 4 dogs, 7 cats, and 42 gold fish."
14+
# => ["4"]
15+
{% endhighlight %}
16+
1017
## Solution
1118

1219
{% highlight coffeescript %}
@@ -32,6 +39,29 @@ RegExp::execAll = (haystack) ->
3239
# => [["4 dogs","4","dogs"],["7 cats","7","cats"],["42 gold","42","gold"]]
3340
{% endhighlight %}
3441

35-
The first line of `execAll` prevents an infinite loop caused by non-global expressions. This could be further improved by creating a clone of the RegExp that is global, and use that.
42+
The first line of `execAll` prevents an infinite loop caused by non-global expressions. This could be further
43+
improved by creating a clone of the RegExp that is global, and use that.
3644

45+
You must not save a reference to this expression (like `a = /xyx/g`) if you plan to call `execAll` more than once.
46+
The same behavior be observed with the regular `exec` method.
47+
48+
{% highlight coffeescript %}
49+
s = "I have 4 dogs, 7 cats, and 42 gold fish."
50+
myRegEx = /\d+/g
51+
myRegEx.exec s
52+
# => ["4"]
53+
myRegEx.execAll s
54+
# => ["7", "42"]
55+
myRegEx.exec s
56+
# => null
57+
{% endhighlight %}
58+
59+
Instead use:
60+
61+
{% highlight coffeescript %}
62+
/\d+/g.execAll s
63+
# => ["4", "7", "42"]
64+
/\d+/g.execAll s
65+
# => ["4", "7", "42"]
66+
{% endhighlight %}
3767

0 commit comments

Comments
 (0)