1

I dont understand the conditional regex.

Using preg_match

I try to get

  • always 4 matches
  • in middle there is an optional dash
  • at the end there is an optional int

Example:

aaa-bbb-ccc-1

"aaa" should be matches[1]

"bbb" should be matches[2]

"ccc" should be matches[3]

"1" should be matches[4]

But there can be an optional dash in bbb. Also the last is optional.

Fe.

aaa-bbb-bbb-ccc

"aaa" should be matches[1]

"bbb-bbb" should be matches[2]

"ccc" should be matches[3]

"" should be matches[4]

What i got so far:

^(\w+)-(\w+)-(\w+)-(\d)$

This works simple with 4 groups.

1-3 expected as letter, number, underscore.

4 expected as digit.

But i dont know how to use the conditions (http://php.net/manual/de/regexp.reference.conditional.php).

Online test: https://regex101.com/r/Ln3f3I/2

Thanks for helping /cottton

1 Answer 1

1

You may use this regex with an optional last group and a non-greedy quantifier in 2nd group:

^(\w+)-([\w-]+?)-(\w+)(?:-(\d+))?+$

Updated RegEx Demo

Regex Details:

  • ^(\w+)-: Match 1+ word characters at start in 1st group followed by -
  • ([\w-]+?)-: Match 1+ word or hyphen characters in 2nd group (lazy) followed by -
  • (\w+): Match 1+ word characters in 3rd group
  • (?:-(\d+))?+$: An optional group with hyphen and digits at the end.
Sign up to request clarification or add additional context in comments.

Comments

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.