SRichardson
SRichardson

Reputation: 13

Node.js regular expression non-capture group in semver

I'm trying to understand how semantic version works in nodejs (and npm). The git repo which hosts the regex used by nodejs is here https://github.com/sindresorhus/semver-regex, but I've copied the only two lines of code below.

'use strict';
module.exports = () => /\bv?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\da-z-]+(?:\.[\da-z-]+)*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?\b/ig;

This uses non-capture groups (?:...) for every group as far as I can tell. How does this work? The matches seem to return values despite not capturing anything. Am I missing a capture group? Is this something non-standard in nodejs?

Upvotes: 1

Views: 590

Answers (1)

user3335966
user3335966

Reputation: 2745

It's obviously for test - it just return true or false;
For exec first result will be value for full regex entrance. So it will be something like:

// r = /\bv?(?:0|[1-9]\d*)\.(?:...
r.exec('1.0.1');// => Array [ "1.0.1" ];

And without ?: as result we will have all groups as array values, like:

// r = /\bv?(0|[1-9]\d*)\.(...
r.exec('1.0.1');// => Array(8) [ "1.0.1", "1", "0", "1", undefined, undefined, undefined, undefined ]

More than that, exec will always return result for regex, as first element (if it exist), even if you will have regex like:

/(?:a)/.exec('a');// => Array [ "a" ]

I hope, I understood question correctly;

Upvotes: -1

Related Questions