1

I try to learn Javascript RegExp and got this RegEx somewhere:

"1234567890".match(/(\d{3})+(?!\d)/g) 
["234567890"] //result from log

I could not understand why it is like this. any help explaining this would be appreciated. Thanks!

TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86
praHoc
  • 315
  • 4
  • 14
  • 1
    please don't ask questions like teach me this and that. – karan Jul 23 '16 at 04:01
  • As the old man said "If you can't explain it to a six-year old, you really don't understand it yourself. if you can teach people to understand thing they don't ask very much. is that not stackoverflow is all about? – praHoc Jul 23 '16 at 04:38
  • 1
    dear @praHoc : please see this before asking anything http://stackoverflow.com/help/how-to-ask – karan Jul 23 '16 at 04:50
  • @karan Thank you for your helpng with the link! – praHoc Jul 23 '16 at 08:30
  • 1
    @karan The page you linked to doesn't prohibit this kind of question in any manner. BTW such questions are pretty common on SO. – cFreed Jul 23 '16 at 17:13
  • @cFreed Thank you very much for clarity, Cheer! – praHoc Jul 25 '16 at 01:13

1 Answers1

0

The regex matches groups of digits with the condition that the group length must be a multiple of 3 and the character trailing the group cannot be a digit.


This is how it works:

(\d{3})        // match exactly 3 digits
       +       // 1 to n times
        (?!\d) // Negative lookahead - assert that the next character is not a digit

More about lookaheads.


In your test string, the only possible match is the one returned from the match() call.

See the following snippet for another example:

var matches = "1234foobar5678901".match(/(\d{3})+(?!\d)/g);
console.log(matches); // ["234", "678901"]
Community
  • 1
  • 1
TimoStaudinger
  • 34,772
  • 13
  • 76
  • 86
  • Thank, I still don't undertand why the result not ['123456789'] instead ['234567890']? – praHoc Jul 23 '16 at 03:01
  • That's what the negative lookahead is for - `123456789` is followed by a `0`, so wouldn't satisfy the condition. `234567890` however is not followed by a digit, and covered by the regex. – TimoStaudinger Jul 23 '16 at 03:04
  • Thank for example, can I say look for d*3 to N time behind (?!\d)? my head fu*k up with regex! at the moment. – praHoc Jul 23 '16 at 03:35
  • I learned a lot from the link you gave! and found that Javascript did not support lookbehind! Just get my head around after 5hours! – praHoc Jul 23 '16 at 08:32