zProgrammer
zProgrammer

Reputation: 739

Regex modifying text

Can I concatenate text to other text using regex?

I have a string consisting of:

"bird dog fish"

I would like to output:

"bird catdog fish"

Would I use gsub to accomplish this? I'm getting confused because, if I match "dog" using gsub, I would have to replace "dog" with "catdog" instead of just adding "cat" to the front of it. How can I just add some text to a specific match? Do I have to use scan or something?

Upvotes: 3

Views: 50

Answers (1)

voithos
voithos

Reputation: 70552

What's wrong with doing replacement?

>>> "bird dog fish".gsub(/(dog)/, 'cat\1')
=> "bird catdog fish"

The \1 is a reference to the (dog) captured group. Of course, (dog) could be any valid regex, so this example could easily be used in more complex situations.

You can have more than one capturing group, if you need to.

>>> "bird dog fish".gsub(/(dog)(.*)(sh)/, 'cat\1\3\2')
=> "bird catdogsh fi"

Ruby 1.9 introduced named capture groups:

>>> "bird dog fish".gsub(/(?<mydog>dog)/, 'cat\kmydog')
=> "bird catdog fish"

This is Ruby. There's always many ways to do it. More can be found in the standard documentation.

Upvotes: 5

Related Questions