I know how to use regular expressions to find the first match of a
pattern in a string. But, how do I most easily find multiple matches?
For example, if the string is
s = ‘abcde_abcde_abcde’
and I want to find the location of ALL the ‘b’ characters, how do I do
it? If I use
m = s.match(/b/)
then m.offset(0) => [1,2]
but I don’t have any information about the second or third occurences of
‘b’.
I know how to use regular expressions to find the first match of a
pattern in a string. But, how do I most easily find multiple matches?
For example, if the string is
s = ‘abcde_abcde_abcde’
and I want to find the location of ALL the ‘b’ characters, how do I do
it?
string = “abcde abcde abcde”
sum = 0
result = []
blocks = string.split(/b/)
blocks.pop
blocks.each do |block|
sum += block.length
result << sum
sum += 1
end
p result # [1,7,13]
s = ‘abcde_abcde_abcde’
m = s.scan(/b/)
p m # [‘b’,‘b’,‘b’]
Thanks Andrea. But is there a way to also find the locations (indexes)
of the ‘b’ characters?
irb(main):012:0> s="a "*5
=> "a a a a a "
irb(main):013:0> s.scan(/a+/) { p $~, $~.offset(0) }
#<MatchData “a”>
[0, 1]
#<MatchData “a”>
[2, 3]
#<MatchData “a”>
[4, 5]
#<MatchData “a”>
[6, 7]
#<MatchData “a”>
[8, 9]
=> "a a a a a "
irb(main):014:0>