# Replacing based on regular ecpressions

**URL:** <https://www.ruby-forum.com/t/replacing-based-on-regular-ecpressions/132154>\
**Category:** Ruby\
**Created:** [March 17, 2008, 1:46pm UTC](https://www.ruby-forum.com/t/replacing-based-on-regular-ecpressions/132154 "2008-03-17T13:46:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![T\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e0b2c6/32.png) [@T\_K](https://www.ruby-forum.com/u/T_K)\
**Post date:** [March 17, 2008, 1:46pm UTC](https://www.ruby-forum.com/t/replacing-based-on-regular-ecpressions/132154/1 "2008-03-17T13:46:46Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![T\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e0b2c6/32.png) [@T\_K](https://www.ruby-forum.com/u/T_K)\
**Post date:** [March 17, 2008, 2:11pm UTC](https://www.ruby-forum.com/t/replacing-based-on-regular-ecpressions/132154/2 "2008-03-17T14:11:06Z")

</div>

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
