[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

String extraction using RegExp

Unmesh Gundecha

6/9/2008 10:06:00 AM

Hi,

I want to extract "New User Registration" and "New User" from a string
as follows. I am using RegExp for this.

r1 = Regexp.new('\(\"([^\.]*)\"\)')
matches = r1.match('Page("New User Registration").Frame("New User")')

puts !matches.nil?
puts matches[0]
puts matches[1]
puts matches[2]

However above code returns only "New User Registration". Is there any
way to find the next match. Is something missing in this code?

Please advice.

Thanks in advance,
Unmesh
--
Posted via http://www.ruby-....

2 Answers

Stefano Crocco

6/9/2008 10:17:00 AM

0

On Monday 09 June 2008, Unmesh Gundecha wrote:
> Hi,
>
> I want to extract "New User Registration" and "New User" from a string
> as follows. I am using RegExp for this.
>
> r1 = Regexp.new('\(\"([^\.]*)\"\)')
> matches = r1.match('Page("New User Registration").Frame("New User")')
>
> puts !matches.nil?
> puts matches[0]
> puts matches[1]
> puts matches[2]
>
> However above code returns only "New User Registration". Is there any
> way to find the next match. Is something missing in this code?
>
> Please advice.
>
> Thanks in advance,
> Unmesh

Regexp.match and String.match only return the first match. If you want to get
all matches, you can use either String#scan or class StringScanner. In your
case, I think the better choice is the former:

str = 'Page("New User Registration").Frame("New User")'
str.scan(r1)
=> [["New User Registration"], ["New User"]]

String#scan scans the string for all matches and returns an array of arrays.
Each subarray contains all the groups for the corresponding match (if the
regexp doesn't contain groups, then String#scan returns an array of strings,
each of which is the matched text).

I hope this helps

Stefano

Unmesh Gundecha

6/9/2008 10:52:00 AM

0

Stefano Crocco wrote:
> Regexp.match and String.match only return the first match. If you want
> to get
> all matches, you can use either String#scan or class StringScanner. In
> your
> case, I think the better choice is the former:
>
> str = 'Page("New User Registration").Frame("New User")'
> str.scan(r1)
> => [["New User Registration"], ["New User"]]
>
> String#scan scans the string for all matches and returns an array of
> arrays.
> Each subarray contains all the groups for the corresponding match (if
> the
> regexp doesn't contain groups, then String#scan returns an array of
> strings,
> each of which is the matched text).
>
> I hope this helps
>
> Stefano

Thanks Stefano,

String#scan worked for me.

Cheers!!
Unmesh
--
Posted via http://www.ruby-....