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
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
On 12/7/06, Ingo W. [email protected] wrote:
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
On 12/6/06, Ingo W. [email protected] wrote:
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.
On 12/7/06, Max M. [email protected] wrote:
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
On 06.12.2006 22:44, Martin DeMello wrote:
i
require ‘enumerator’
=> true“banana”.to_enum(:scan, /a/).inject(0) {|s,| s+1}
=> 3
robert
Thank you very much for all your great suggestions!
Ingo
On 2006-12-07 04:02:55 -0500, Robert K. [email protected]
said:
banana.scan(/a/) { i += 1}
irequire ‘enumerator’
=> true
“banana”.to_enum(:scan, /a/).inject(0) {|s,| s+1}
=> 3robert
banana.split(‘’).reject { |i| i if i != ‘a’ }.length
I want extra points for using “banana.split”.
Best,
James
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs