Is there something like Regexp#match_all

A

Andi Schacke

Hi,

is there a possibility to return all the matches of a regexp? or in
other words is there a way to apply a block to all matches at once?
Something like String#gsub but where I can specifiy what to do with the
matches...

Thanks
Andi
 
A

Austin Ziegler

is there a possibility to return all the matches of a regexp? or in
other words is there a way to apply a block to all matches at once?
Something like String#gsub but where I can specifiy what to do with the
matches...

These things are actually two different things.

1. Look at String#scan
2. Look at String#gsub with the block form and use Regexp::last_match
(it's a thread-local value, IIRC).

-austin
 
R

Robert Klemme

is there a possibility to return all the matches of a regexp? or in
other words is there a way to apply a block to all matches at once?
Something like String#gsub but where I can specifiy what to do with the
matches...

What exactly do you want to do with matches?

robert
 
A

Andi Schacke

Robert said:
What exactly do you want to do with matches?

robert

I'd like to build a small web-tool for myself to highlight all the
matches of a regexp against a specified string (e.g. the matches should
be in a different color). But I think I found a solution:

source_string.gsub(regexp) {|match| "<span
style=\"color:red;\">#{match}</span>"}
 
J

James Edward Gray II

I'd like to build a small web-tool for myself to highlight all the
matches of a regexp against a specified string (e.g. the matches
should
be in a different color). But I think I found a solution:

source_string.gsub(regexp) {|match| "<span
style=\"color:red;\">#{match}</span>"}

You don't really need the block form for such a simple replacement.
This is the same thing:

source_string.gsub(regexp, '<span color="red">\&</span>')

James Edward Gray II
 
R

Robert Klemme

You don't really need the block form for such a simple replacement.
This is the same thing:

source_string.gsub(regexp, '<span color="red">\&</span>')

.... and in fact more efficient IIRC.

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

Forum statistics

Threads
474,433
Messages
2,571,683
Members
48,796
Latest member
Greg L.

Latest Threads

Top