Ruby regex what does the \1 mean for gsub -


what \1 do?

for example

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

i believe has how use parentheses, i'm not sure. explain me? , can stuff \2? if so, do?

each item surround parenthesis in searching part correspond number \1, \2, etc., in substitution part.

in example, there's 1 item surrounded parenthesis, "(bar)" item, anywhere put \1 part inside parenthesis, swapped in. can put in \1 multiple times, handy if want repeat found item, legitimately write car\1\1\1 , "bar" swapped in 3 times.

there's no use \2 because there's 1 item surrounded parentheses. however, if had (bar)(jar), \1 represent "bar" , \2 represent "jar".

you things this:

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

which become:

barjarbarjarjarbar 

here's real-world example comes in handy. let's have name list this:

jones, tom   smith, alan   smith, dave   wilson, bud 

and want change this:

tom jones   alan smith   dave smith   bud wilson 

you search for:

(.+), (.+) 

and replace with:

\2 \1 

you replace with:

\1: \2 \1   

which become:

jones: tom jones   smith: alan smith   smith: dave smith   wilson: bud wilson 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -