How to find multiple matches in a string

A

Alex DeCaria

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'.

--Alex
 
I

Intransition

I know how to use regular expressions to find the first match of a
pattern in a string. =A0But, how do I most easily find multiple matches?
For example, if the string is

s =3D 'abcde_abcde_abcde'

and I want to find the location of ALL the 'b' characters, how do I do
it?

Try #scan
 
A

Alex DeCaria

Andrea said:
Hei,

s = 'abcde_abcde_abcde'
m = s.scan(/b/)
p m # ['b','b','b']

HTH

Thanks Andrea. But is there a way to also find the locations (indexes)
of the 'b' characters?

--Alex
 
A

Andrea Dallera

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]

Don't tell anyone I've written this crap :)

--
Andrea Dallera
http://github.com/bolthar/freightrain
http://usingimho.wordpress.com


Andrea said:
Hei,

s = 'abcde_abcde_abcde'
m = s.scan(/b/)
p m # ['b','b','b']

HTH

Thanks Andrea. But is there a way to also find the locations (indexes)
of the 'b' characters?

--Alex
 
C

Caleb Clausen

Andrea said:
Hei,

s = 'abcde_abcde_abcde'
m = s.scan(/b/)
p m # ['b','b','b']

HTH

Thanks Andrea. But is there a way to also find the locations (indexes)
of the 'b' characters?

I think this works:

s = 'abcde_abcde_abcde'
i=0
while i=s.index('b',i)
do_something_with i
end
 
R

Robert Klemme

Andrea said:
Hei,

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>

Kind regards

robert
 

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,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top