Nikita Alexandrovich
Nikita Alexandrovich

Reputation: 25

How to write right regex for route?

In my Phpdoc I have such setting for route.

* @route   /v1/posts/<type:(news|article|release|about)?>

How to make it so that the slash after the "posts" was inserted only when the type is passed.

Upvotes: 2

Views: 71

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626774

You may make the type alternation group obligatory and wrap the /type.. part with an optional non-capturing group:

/v1/posts(?:/<type:(news|article|release|about)>)?

Now,

  • /v1/posts - matches a literal substring
  • (?:/<type:(news|article|release|about)>)? - matches 1 or 0 occurrences (i.e. this part may be missing) of
    • / - a slash
    • <type:(news|article|release|about)> - <type:, then any of the alternatives inside the capturing group, and then >.

Upvotes: 1

Related Questions