0

I need to support endpoints such as

/myendpoint:
/v1/myendpoint:
/v3/someotherendpoint:

This regex:

const regexPattern = '/[a-zA-Z0-9-]+:';

Only answers to /myendpoint:

How can we do an or operation to support both cases ?

JAN
  • 21,236
  • 66
  • 181
  • 318
  • Add a match for zero or more subsequent sequences like the first one, starting with `/`. – Pointy Apr 14 '22 at 13:31
  • This can help https://stackoverflow.com/questions/7124778/how-to-match-anything-up-until-this-sequence-of-characters-in-a-regular-expres. – Samball Apr 14 '22 at 13:36

2 Answers2

2

If you just need to test if it matches or not, you can just use a repeated pattern, like this:

const tests = ['/a', '/a/b/c', 'nope'];
const pattern = /^(\/[0-9a-z-]+)+$/i;

tests.forEach(str => console.log(str, pattern.test(str)));

If you want to match each part, it gets a lot trickier and uglier, and you'd better off testing if it works then just use split('/') to get the parts.

samanime
  • 25,408
  • 15
  • 90
  • 139
1

Just make it something like recursive your existing solution for its multiple instance.

Example: (\/[a-zA-Z0-9-]+)*:

Play: https://regexr.com/6jka3

The character * in a regular expression means "match the preceding character zero or many times"

Shri Hari L
  • 4,551
  • 2
  • 6
  • 18