开发者

What is gsub(/(\d{4})\/(\d\d)\/(\d\d)\/(.*)/, '\1-\2-\3-\4') mean?

I've stumbled upon this on ruby code. I know \d{4})\/(\d\d)\/(\d开发者_开发知识库\d)\/(.*)/ means but what is \1-\2-\3-\4 means?


The \1-\2-\3-\4 are back references to the captured data within the regex itself.

So \1 contains the data that was captured in the first group, \2 was the data captured in the second group, \3 was the data captured in the 3rd group and so on.

See here for the Ruby implementation


Those are backreferences. \1 means the result of the first group of brackets (), ie (\d\d), \2 means the 2nd group and so on.


transform 1234/12/12/XX into 1234-12-12-XX


I think the \1,\2 etc just referer to the matched groups

i.e. \1 == (\d{4})


They refer back to the matched groups (substituion backreferences)

For more info, see http://www.regular-expressions.info/ruby.html


You can capture parts of the pattern of the regular expression by placing them inside parentheses and then on the substitution part reference them with \1,\2,\3,... according to the order they appear.

In your example \1 will be the first 4 digits, \2 will be the second two, \3 will be the following two and \4 will be the rest.

So "20100410milk" will be substituted by "2010-04-10-milk", because \1 will be 2010, \2 04, \3 10 and \4 milk.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜