Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match required and optional parts of string

Tags:

regex

php

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.

like image 594
philipobenito Avatar asked Mar 07 '13 19:03

philipobenito


People also ask

How do I make part of a RegEx optional?

Adding ? after the non-capturing group makes the whole non-capturing group optional. Alternatively, you could do: \".

What does '$' mean in RegEx?

$ means "Match the end of the string" (the position after the last character in the string).


1 Answers

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

like image 79
VladL Avatar answered Sep 22 '22 17:09

VladL