You may match the string in question up the optional string starting with /
with any 1 or or more chars other than /
after it up to the end of the string:
\/main\/sections(?:\/[^\/]*)?$
^^^^^^^^^^^^^^
See the regex demo. If you really need to constrain the optional subpart to only consist of just letters and -
with the -
not allowed at the start/end (with length of 2+ chars), use
/\/main\/sections(?:\/[a-z][a-z-]{0,48}[a-z])?$/i
Or, to also allow 1 char subpart:
/\/main\/sections(?:\/[a-z](?:[a-z-]{0,48}[a-z])?)?$/i
Details
\/main\/sections
- a literal substring /main/sections
(?:\/[^\/]*)?
- an optional non-capturing group matching 1 or 0 occurrences of:
\/
- a /
char
[^\/]*
- a negated character class matching any 0+ chars other than /
$
- end of string.
JS demo:
var strs = ['/main/sections/create-new','/main/sections/delete','/main/sections/','/main/sections','/main/sectionsextra'];
var rx = /\/main\/sections(?:\/[^\/]*)?$/;
for (var s of strs) {
console.log(s, "=>", rx.test(s));
}