String extraction using RegExp

  • Thread starter Unmesh Gundecha
  • Start date
U

Unmesh Gundecha

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
 
S

Stefano Crocco

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
 
U

Unmesh Gundecha

Stefano said:
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
 

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,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top