Regex match required and optional parts of string

php, regex

Solution

The question mark makes the preceding token in the regular expression optional. E.g.: `colou?r` matches both `colour` and `color`.

You can make several tokens optional by grouping them together using round brackets, and placing the question mark after the closing bracket. E.g.: `Nov(ember)?` will match `Nov` and `November`.

You can write a regular expression that matches many alternatives by including more than one question mark. `Feb(ruary)?` `23(rd)?` matches `February 23rd`, `February 23`, `Feb 23rd` and `Feb 23`.

Source: http://www.regular-expressions.info/optional.html

Problem

I'd like to do a preg_match on a uri string with optional and required parts but I can't figure it out. Example to match: ``` /segment/(required)/segment(/optional) ``` I want both strings below to match against the above ``` /segment/required/segment/optional ``` and ``` /segment/reguired/segment ``` I know the policy is to not write for me but I can't figure this out so thought I'd at least ask.

Original source