Replacing based on regular ecpressions

T

T K

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
 
R

Robert Klemme

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
 

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,285
Messages
2,571,416
Members
48,107
Latest member
AmeliaAmad

Latest Threads

Top