Skip to content

Conversation

@brigand
Copy link
Contributor

@brigand brigand commented Aug 10, 2013

With regular expressions you often want to find more than the first match. It's pretty easy to do in CoffeeScript.

@sukima
Copy link
Contributor

sukima commented Aug 12, 2013

The problem description leaves me wondering why regular JS doesn't have this. Why does /patter/g not work in this case?

Maybe expanding the problem text to explain that this recipe is a convenience function around manually looping through the results from /pattern/g.

@brigand
Copy link
Contributor Author

brigand commented Aug 12, 2013

It's one of JavaScript's shortcommings. For example, Python has a findall method.

Consider this example. We only get the first match. If we try it again, we get the same match.

s = "I have 4 dogs, 7 cats, and 42 gold fish."
/\d+/g.exec(s)
# => ["4"]
/\d+/g.exec(s)
# => ["4"]

Now, we save a reference to our expression. This lets us get all of the matches.

myRegEx = /\d+/g
myRegEx.exec s
# => ["4"]
myRegEx.exec s
# => ["7"]
myRegEx.exec s
# => ["42"]
myRegEx.exec s
# => null

By using the prototype we are sure we're always referencing the same regex, and it's a lot more succinct than saving a reference to each expression we would like to use, and less error prone. I'm not sure exactly how to explain this in the usual couple of sentences that the problem definition is.

Any ideas?

@sukima
Copy link
Contributor

sukima commented Aug 14, 2013

Yeah! makes more sense now. :shipit:

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be /\d+/g

@brycec
Copy link

brycec commented Aug 16, 2013

Alternatively, you could just use String.match with a global regex, like so:

"I have 4 dogs, 7 cats, and 42 gold fish.".match /\d+/g # -> ["4", "7", "42"]

@brigand
Copy link
Contributor Author

brigand commented Aug 16, 2013

Huh, I forgot about that. Nevermind, this page isn't needed.

@brigand brigand closed this Aug 16, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants