Ruby regex what does the \1 mean for gsub

后端 未结 3 2084
一生所求
一生所求 2021-02-01 08:20

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 parenthese

3条回答
  •  萌比男神i
    2021-02-01 08:31

    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
    

提交回复
热议问题