阅读背景:

为什么gsub的'\ 1'捕获组产生这个字符串?

来源:互联网 

I am confused as to why I am capturing this pattern via '

I am confused as to why I am capturing this pattern via '\1' grouping. I am capturing two digits at a time, but why does it skip here:

我很困惑为什么我通过'\ 1'分组捕获这个模式。我一次捕获两位数,但为什么跳过这里:

"123 456 789".gsub(/(\d)(\d)/, '\1')
=> "13 46 79"

I can understand that '\0' gives me the original string:

我能理解'\ 0'给了我原始的字符串:

"123 456 789".gsub(/(\d)(\d)/, '\0')
=> "123 456 789"

This also confuses me, but I can understand '\2' once I learn what '\1' is doing:

这也让我感到困惑,但是一旦我知道'\ 1'正在做什么,我就能理解'\ 2':

"123 456 789".gsub(/(\d)(\d)/, '\2')
=> "23 56 89"

2 个解决方案

#1


4  

The regex matches "12", "45", "78", and gsub replaces them with "1", "4", "7", respectively, giving "13 46 79".

正则表达式匹配“12”,“45”,“78”,并且gsub分别用“1”,“4”,“7”替换它们,给出“13 46 79”。

#2


2  

To obtain 12 45 78, you need to use

要获得12 45 78,您需要使用

(\d)\d\b

And replace with \1.

并替换为\ 1。

See demo

见演示

Here, we match a digit and capture it ((\d)), then we match another digit (with \d) that is right before a word boundary \b.

在这里,我们匹配一个数字并捕获它((\ d)),然后我们匹配在字边界\ b之前的另一个数字(\ d)。

IDEONE demo:

IDEONE演示:

puts "123 456 789".gsub(/(\d)\d\b/, '\1')

' grouping. I am capturing two digits at a time, but why does it skip here:I am confused as to why I am capturing this pat




你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: