简体   繁体   中英

Javascript RegExp finding digit grouping

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!

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"] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM