Get Number of regex matches

I

Ingo Weiss

Hi,

how can I get the NUMBER of matches for a regular expression in a given
string?

For example: for string 'Banana' and regex /a/ I should get '3'
(matches)

Thanks!
Ingo
 
M

Max Muermann

Hi,

how can I get the NUMBER of matches for a regular expression in a given
string?

For example: for string 'Banana' and regex /a/ I should get '3'
(matches)

Here's one way (but there are probably better ones):

"Banana".scan(/a/).size
=> 3

max
 
W

Wilson Bilkovich

Hi,

how can I get the NUMBER of matches for a regular expression in a given
string?

For example: for string 'Banana' and regex /a/ I should get '3'
(matches)

One way is:
'Banana'.scan(/a/).size

I'm not sure how to get it out of the MatchData returned by 'match' or
=~, unfortunately.
 
M

Martin DeMello

Here's one way (but there are probably better ones):

"Banana".scan(/a/).size
=> 3

This one skips the intermediate array construction in return for some
clunkiness:

i = 0
banana.scan(/a/) { i += 1}
i

martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top