首页 > 解决方案 > PHP conditional regex

问题描述

I dont understand the conditional regex.

Using preg_match

I try to get

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

标签: phpregexconditional

解决方案


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.

推荐阅读