1

I am trying to define a route in express js that takes an unknown amount N of parameters. It should match the following routes, capturing all digit groups:

/scope

/scope/1/12

/scope/1/12/123

etc.

I wrote a regex for the matching of the n-amount of numbers, as follows:

/(?:\/?(\d+)\/?)/g

The global /g however doesn't seem to be allowed, see (The regex parser of express js on github). Am I doing something wrong here? I could solve this very ugly and dirty by doing something like:

^\/scope\/?(\d+)?\/?(\d+)?\/?(\d+)?

But this is not dynamic, feels dirty and if I add deeper levels of scoping I always will need to add more /?(\d+) regex parts, which is a model that does not fit my business logic. I am shure there must be a better way...

Okay, after a discussion with @vks, which was useful but unfortunately not answering the question, we came to the conclusion that this is not a regex problem. With the \g modifier a regex capturing all digit groups can quite easily be written, even in javascripts very limited regex engine.

The question now becomes more clearly formulated: since expressjs does not allow a full regex from begin to end, but rather encloses the regex you use in a route in it's own begin and end of a regex, not allowing /g modifiers, what is the expressjs idiomatic way to solve this problem?

1 Answer 1

1
^\/scope(?:\/\d+)*$

You can try this.See demo.

https://regex101.com/r/eZ0yP4/30

Sign up to request clarification or add additional context in comments.

5 Comments

The problem with this is that it matches only the last parameter. regex101.com/r/eI9pV0/1 (see matches in the right corner)
I am sorry, the matches are indeed correct. Problem is the capturing of the digit groups. In expressjs, as far as I understand this, you need al parameters to be in () capture groups. (Also, if you see the github link provided, I am affraid I can't set the global flag)
The regex works and does what it needs to do. But have a look at the github link, I can't use a global flag...
@Quant does your engine support \G or \K flag

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.