1

Take a given URI, like this:

one/two/three

How would I match each character, in a capture group, between the slashes? This can be done with this method:

(.+)\/(.+)\/(.+)

This gives me three groups where:

$1 = one
$2 = two
$3 = three

What I am having trouble with is making a capture group optional. I thought that this would work, thinking I could make each group optional (match zero or more):

(.+)?\/(.+)?\/(.+)?

Is there a way, using Regex or PHP to optionally match parts one, two or three of the above URI?

1 Answer 1

1

You can use the following regex

^(?:(.+?))?(?:\/(.+?))?(?:\/(.+?))?$

This will make all groups optional. The main point is using non-capturing groups with ? quantifier, and .+? patterns to capture each part into separate group, so that you could reference them later with $n.

See example.

Sample code:

$re = "/^(?:(.+?))?(?:\\/(.+?))?(?:\\/(.+?))?$/m"; 
$str = "one/two/three\none/two\none\n\n"; 
preg_match_all($re, $str, $matches);
Sign up to request clarification or add additional context in comments.

2 Comments

This matches parts one, two or three optionally, however I wanted each matched part (one, two or three) inside a capture group so I can reference them using $1, $2, or $3. Is this possible?
Ok, I think I will just make answer a bit shorter. :). All you need is to use non-greedy quanifiers (with .+?).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.