Skip to content

Commit 2e47789

Browse files
author
root
committed
added finding all matches page
1 parent bf6de67 commit 2e47789

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
layout: recipe
3+
title: Finding All Matches
4+
chapter: Regular Expressions
5+
---
6+
## Problem
7+
8+
You need to find all matches, not just the first.
9+
10+
## Solution
11+
12+
{% highlight coffeescript %}
13+
RegExp::execAll = (haystack) ->
14+
return [] unless @global
15+
match[0] while match = @exec haystack
16+
17+
text = "I have 4 dogs, 7 cats, and 42 gold fish."
18+
/d+/g.execAll text
19+
# => ["4", "7", "42"]
20+
{% endhighlight %}
21+
22+
## Discussion
23+
24+
The above throws away submatches, in order to simplify the result. You can keep them with this variant.
25+
26+
{% highlight coffeescript %}
27+
RegExp::execAll = (haystack) ->
28+
return [] unless @global
29+
match while match = @exec haystack
30+
31+
/(\d+) (\w+)/g.execAll "I have 4 dogs, 7 cats, and 42 gold fish."
32+
# => [["4 dogs","4","dogs"],["7 cats","7","cats"],["42 gold","42","gold"]]
33+
{% endhighlight %}
34+
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.
36+
37+

0 commit comments

Comments
 (0)