how to find the position of each match within a string

L

Li Chen

Hi all,

I have a small script to find a match. If a match is found I need to
print its position within the string. I try the String#index but it only
returns the first match. Any idea?

Thanks,

Li

C:\Documents and Settings\chen73\My Documents\Ruby\bin>irb
irb(main):001:0> "ello-hello".scan('e') do |match|
irb(main):002:1* p "ello-hello".index(match)
irb(main):003:1> end
0
0
=> "ello-hello"
irb(main):004:0>
 
A

Albert Schlef

You can examine the $~ global MatchData object, in a couple of ways:
irb(main):003:0> "ello-hello".scan('e') do |match|
irb(main):004:1* p $~.pre_match.size
irb(main):005:1> end
0
6

Interesting. Does that mean that String#scan() converts a String
argument to RegExp?
 
A

Albert Schlef

Radosław Bułat said:
Yes it does, even if it search fixed-size string.

I'm shocked. Why does it do this? (this conversion)

And doesn't this mean that #scan is less efficient than it could have
been? Isn't matching regexps slower than matching plain strings?
 
L

Li Chen

David said:
You can examine the $~ global MatchData object, in a couple of ways:

irb(main):003:0> "ello-hello".scan('e') do |match|
irb(main):004:1* p $~.pre_match.size
irb(main):005:1> end
0
6
=> "ello-hello"
irb(main):006:0> "ello-hello".scan('e') do |match|
irb(main):007:1* p $~.offset(0)[0]
irb(main):008:1> end
0
6
=> "ello-hello

Hi David,

Thanks.

I go back and read the chapter about MatchData. And it helps me a lot.

Li
 

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

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top