3

I know javascript "(x)" can memorize pattern and match ,but I have a question about it. here is my code:

 var re = /(\w*)(abc)\1\2/;
 var str = '123dabc123dabc'
 console.log(re.exec(str))

 var re = /(\w*)(abc)\1\3/;
 var str = '123dabc123dabc'
 console.log(re.exec(str)) // this must be null,because "\3" is not the right pattern,but what·s the "\3" ·s match rules in here

I want to know which str \3 can match ?...

Liam
  • 22,818
  • 25
  • 93
  • 157
NC LI
  • 69
  • 1
  • 1
  • 5

1 Answers1

4

When refering to a capturing group index that does not exist, it refers to the character index.

So \3 matches the character ?? with index 3^8 (3^10 or 3^16) literally

?? because no character is mapped to this. If you had written another octal value, like let's say \51 you would have matched ). Note that if you (think) you use \48 as an octal value, this will not work, it will be treated as \4 followed by literal 8

It is very similar to when you are using hexadecimal, you might have seen \x30 for example...

\x30 matches the character 0 with index 30^16 (48^10 or 60^8) literally

Salketer
  • 11,628
  • 2
  • 23
  • 56
  • http://www.rexegg.com/regex-capture.html helped me to better understand this answer. And http://www.asciitable.com/ shows octal `3` matching the "End of Text" character. – StriplingWarrior Sep 06 '17 at 15:07
  • 1
    Thanks! I was actually looking for the exact character... Hence why I wanted to give an example with an actually readable character. regex101.com is also very fun as it gives you in real time the token matches, so you can play with it and understand the behaviour. – Salketer Sep 06 '17 at 15:10