How to find out pattern'cat' in this string='ccccatgggctacatgggtcat'
? There are three 'cat' within the string and I want to return the
position of each match.
Although # match return the match , #pre_match and #post_match do the
tricks but they only work for the first match. How about the 2nd, third
match, and more? I try #scan(pattern) but it doesn't return the
position for each match. I wonder how other handle this problem.
How to find out pattern'cat' in this string='ccccatgggctacatgggtcat'
? There are three 'cat' within the string and I want to return the position of each match.
there is String#index.
there is no indexes, but you can build one if you like
eg,
s
=> "ccccatgggctacatgggtcat"
class String
def indexes str, n=0
n=index( str, n)
if n
[n] + indexes( str, n+=1)
else
end
end
end
=> nil
s.indexes "cat"
=> [3, 12, 19]
the faster way is to loop, but i just want to test my recursion skill
best regards
-botp
···
On Thu, May 28, 2009 at 9:34 PM, Li Chen <chen_li3@yahoo.com> wrote:
while x = s.index('cat', (pos.last||-1)+1)
pos << x
end
=> nil
pos
=> [3, 12, 19]
String#index is the way to go. The second arg is the position to start looking for a match. .last==nil so it is a small trick to make the first loop test pass a 0 or 1 more than the previous match position.