Ruby regex \ 1对gsub意味着什么 [英] Ruby regex what does the \1 mean for gsub

查看:72
本文介绍了Ruby regex \ 1对gsub意味着什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

\ 1的作用是什么?

例如

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

我相信这与您使用括号的方式有关,但是我不确定.有人可以向我解释吗?而且你可以做\ 2之类的东西吗?如果是这样,那该怎么办?

解决方案

在搜索部分中用括号括起来的每个项目将与替换部分中的数字\1\2等相对应. /p>

在您的示例中,圆括号中只有一个项"(bar)",因此放置\1的任何位置都将被替换为圆括号内的部分.您可以放入\1多次,这很方便,如果您想重复找到的项目,那么您可以合法地写car\1\1\1,而"bar"将被交换三次.

\2没有用,因为括号中只有一个项目.但是,如果您有(bar)(jar),则\1将代表"bar",而\2将代表"jar".

您甚至可以执行以下操作:

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

将变为:

barjarbarjarjarbar

这是一个方便使用的真实示例.假设您有一个这样的姓名列表:

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

,您想将其更改为此:

Tom Jones  
Alan Smith  
Dave Smith  
Bud Wilson

您可以搜索:

(.+), (.+)

并替换为:

\2 \1

您也可以替换为:

\1: \2 \1  

将会成为:

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

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?

解决方案

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

这篇关于Ruby regex \ 1对gsub意味着什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆