php - PHP conditional regex
问题描述
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
解决方案
You may use this regex with an optional last group and a non-greedy quantifier in 2nd group:
^(\w+)-([\w-]+?)-(\w+)(?:-(\d+))?+$
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.
推荐阅读
- angular - 如何修复 html 文件中的注销按钮无法识别(单击)
- excel - 如果 F 列包含“A”,则将 C 列中的单元格设为“Apples”
- vb.net - 使用 TabControl 时控制程序顺序
- sql-server - SQL Server XML - 修改多个元素
- algorithm - 固定大小数组线性搜索的大O
- sql-server - 具有 ROW_NUMBER 逻辑问题的嵌套子查询
- excel - 无法在 Excel 中通过 ADODB 连接运行 Access 查询
- python - 如何匹配数据框中列之间的值
- python - 将输入层与另一个顺序模型一起传递到自定义损失函数中
- python-3.x - Python中字符串的重叠值