2

I'm trying to write a regex to match an optional parameter at the end of a path.
I want to cover the first 4 paths but not the last one:

/main/sections/create-new
/main/sections/delete
/main/sections/
/main/sections
/main/sectionsextra

So far I've created this:

/\/main\/sections(\/)([a-zA-z]{1}[a-zA-z\-]{0,48}[a-zA-z]{1})?/g

This only finds the first 3. How can I make it match the first 4 cases?

ctwheels
  • 21,901
  • 9
  • 42
  • 77
Reyraa
  • 4,174
  • 2
  • 28
  • 54

1 Answers1

2

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));
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Yes, it works. there's just one problem about it, it also matches if the optional part is space separated. – Reyraa Sep 27 '17 at 13:35
  • 1
    @Reyraa Do you mean the last subpart cannot have whitespace? Just add `\s` to the negated character class, `[^\/]` => `[^\/\s]`. Also, forgot to add that [`[A-z]` matches more than just letters](https://stackoverflow.com/questions/29771901/why-is-this-regex-allowing-a-caret/29771926#29771926). I added some more variations to show how far you may go here with the restrictions. – Wiktor Stribiżew Sep 27 '17 at 14:11