Regular expression back reference inside the group it references

时间:2016-02-03 03:28:15

标签: regex backreference

Just encountered a regex which I have never seen before because I'd have never thought to try it:

((hello)\2)

I would have assumed this is an error. The back reference is referencing the group that it's actually in. This seems valid though and will match:

hellohello

Can someone explain the logic please? I presume this falls under the category of a nested back reference (or maybe even a forward reference) but the logic employed is unclear to me.

This case seems similar to "Nested References" here http://www.regular-expressions.info/backref2.html but it's not the same as far as I can see.

FYI I'm already 99.9% sure I'd never use this in a production environment. I don't think I'd wish that upon any colleague!

1 个答案:

答案 0 :(得分:2)

((hello)\2)

^====1st group
 ^===2nd group

2nd群组包含hello\2与之匹配。因此True获得hellohello