[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Replacing based on regular ecpressions

T K

3/17/2008 12:45:00 PM

Hi,

I'm writing a ruby script that does a batch search-and-replace command.

In each line of the file that is opened, I would like to delete part
of the entire part matched by a regrex. For example,


line.gsub(/(Tennis\/Soccer\/.+?).+?){
puts $& # entire match
puts $1 # the first match

}

I can successfuly identify the parts I need in the regres, now I want
to only keep the first match. Something like "$&" - "$1".


I tried different methods such as String#delete, but they didn't work for me.


-T

1 Answer

Robert Klemme

3/17/2008 1:08:00 PM

0

On 17.03.2008 13:45, T K wrote:
> I'm writing a ruby script that does a batch search-and-replace command.
>
> In each line of the file that is opened, I would like to delete part
> of the entire part matched by a regrex. For example,
>
>
> line.gsub(/(Tennis\/Soccer\/.+?).+?){

That's not a valid regular expression as far as I can see. So the whole
piece of code is not valid Ruby code.

> puts $& # entire match
> puts $1 # the first match

puts is not going to work for replacements.

> }
>
> I can successfuly identify the parts I need in the regres, now I want
> to only keep the first match. Something like "$&" - "$1".

Err, what? Can you please be a bit more specific? What is it that you
want to match and what is your expected output?

Did you maybe mean

line.gsub! %r{Tennis/Soccer/(.+?)}, '\\1'

Note though that .+? will match a single character most of the time if
you do not place another expression with a more specific pattern afterwards.

> I tried different methods such as String#delete, but they didn't work for me.

String#gsub and #gsub! are fine. You just need to use them properly.

Kind regards

robert