1

here are my possible matching cases

/aaa
/aaa/
/aaa/bbb
/aaa/bbb/
/aaa/bbb/ccc
/aaa/bbb/ccc/

I'm trying to catch aaa, bbb and ccc if available

I know or sure aaa is there, so the regex can be /(aaa)/([^/]*)...

I tried a few other scenarios to catch the rest of the words after slash, non-greedy /([^/]+), /([^/].+?), (/[^/].+?), (?:/(.*)) but they don't match all cases.

Any ideas?

One can test here enter link description here

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

1 Answers1

0

You can use this regex with all optional matches after first match:

~^/([^/]+)(?:/([^/]+)(?:/([^/]+))?)?/?$~m

RegEx Demo

RegEx Breakup:

  • ^/ - Match / at start
  • ( - Start captured group #1
    • [^/]+ - Match h1 or more non-slash characters
  • ) - End captured group #1
  • (?: - Start non-capturing group #1
    • / - Match a literal slash
    • ( - Start captured group #2
      • [^/]+ - Match 1 or more non-slash characters
    • ) - End captured group #2
    • (?: - Start non-capturing group #2
      • / - Match literal /
      • ( - Start captured group #3
        • [^/]+ - Match 1 or more non-slash characters
      • ) - End captured group #3
    • )? - End non-capturing group #2 (optional match)
  • )? - End non-capturing group #1 (optional match)
  • /? - Match optional trailing / $ - End of input

EDIT: If you want to match all the components separated by / then you can use:

~(?:^|\G)/([^/\n]+)~m

RegEx Demo 2

anubhava
  • 761,203
  • 64
  • 569
  • 643