Gillespie
Gillespie

Reputation: 6561

What is the purpose of this non-capturing group?

I am trying to understand the inner pipings of express.js, but I'm having a little trouble on one thing.

If you add a new route, like such:

app.get("/hello/darkness/myold/:name", ...)

The string I provided internally becomes a regular expression. Now, I worked out what I thought the regex should be internally, and I came up with:

^\/hello\/darkness\/myold\/([^\/]+?)\/?$

The ([^\/]+?) will capture the name parameter, \/? is present if strict routing is disabled, and the whole thing is encapsulated in ^...$. However, when I went and looked what is actually stored inside express, it's actually this:

^\/hello\/darkness\/myold\/(?:([^\/]+?))\/?$

As you can see, there is a non-capturing group around the capturing group. My question is: what is the purpose of this non-capturing group?


The method I used to see what regex express.js was using internally was simply to make an invalid regex and view the error console:

app.get('/hello/darkness/myold/:friend/[', function(req, res){});

yields

SyntaxError: Invalid regular expression: ^\/hello\/darkness\/myold\/(?:([^\/]+?))\/[\/?$

Upvotes: 0

Views: 57

Answers (1)

Gillespie
Gillespie

Reputation: 6561

The answer to this question is that the non-capturing group is a relic of the case where a parameter is optional. Consider the difference between the following two routes:

/hello/:world/goodbye

/hello/:world?/goodbye

They will generate, respectively:

^\/hello\/(?:([^\/]+?))\/goodbye\/?$

^\/hello(?:\/([^\/]+?))?\/goodbye\/?$

Note the important but subtle change that happens to the non-capturing group when an optional parameter is present.

Upvotes: 0

Related Questions