Ruby regex what does the \1 mean for gsub

Tommy picture Tommy · Apr 5, 2013 · Viewed 21.1k times · Source

What does the \1 do?

For example

"foo bar bag".gsub(/(bar)/,'car\1')

I believe it has something to do with how you use parentheses, but I'm not really sure. Could someone explain it to me? And can you do stuff like \2? If so, what would that do?

Answer

James Toomey picture James Toomey · Apr 5, 2013

Each item that you surround with parenthesis in the searching part will correspond to a number \1, \2, etc., in the substitution part.

In your example, there's only one item surrounded by parenthesis, the "(bar)" item, so anywhere you put a \1 is where the part inside the parenthesis, will be swapped in. You can put in the \1 multiple times, which is handy if you want to repeat that found item, so you could legitimately write car\1\1\1 and "bar" will be swapped in three times.

There's no use for \2 because there's only one item surrounded by parentheses. However, if you had (bar)(jar), then the \1 would represent "bar" and \2 would represent "jar".

You could even do things like this:

\1\2\1\2\2\1

which would become:

barjarbarjarjarbar

Here's a real-world example where this comes in handy. Let's say you have a name list like this:

Jones, Tom  
Smith, Alan  
Smith, Dave  
Wilson, Bud

and you want to change it to this:

Tom Jones  
Alan Smith  
Dave Smith  
Bud Wilson

You could search for:

(.+), (.+)

and replace with:

\2 \1

You could also replace with:

\1: \2 \1  

Which would become:

Jones: Tom Jones  
Smith: Alan Smith  
Smith: Dave Smith  
Wilson: Bud Wilson