首页 > 解决方案 > 带有捕获组的正则表达式

问题描述

我正在尝试将某些模式与正则表达式匹配,并且还能够捕获子模式(完整模式必须有效,应提取子模式。

我的一些模式是:

20170408143311101 _rdds.22; the-context=+39-20170408143311101@127.0.0.1-SET_PARAMETERxml

20170408143311101 _rdds.22;上下文=+39-20170408143311101@127.0.0.1。xml

20170408143311101 _rdds.22;the-context=+39-20170408143311101@127.0.0.1- SET_PARAMETER

20170408143311101 _rdds.22;上下文=+39-20170408143311101@127.0.0.1

20190502085933954 _tel.111; the-tag=+39-20190502085933212@127.12.13.14-TEARDOWNxml

20190502085933954 _tel.111;the-tag=+39-20190502085933212@127.12.13.14- TEARDOWN

20190502085933954 _tel.111;标签=+39-20190502085933212@127.12.13.14

20190502085933954 _tel.111;标签=+39-20190502085933212@127.12.13.14。xml

20190502085928958 _tel.0222; the-context=myco.local-20190502085928958@127.0.0.1-SET_VARIABLExml

20190502085928958 _tel.0222;the-context=myco.local-20190502085928958@127.0.0.1- SET_VARIABLE

20190502085928958 _tel.0222;the-context=myco.local-20190502085928958@127.0.0.1

20190502085928958 _tel.0222;the-context=myco.local-20190502085928958@127.0.0.1。xml

子模式突出显示为:
日期:粗体
类型:普通
属性:粗斜体
ext:斜体

注意:“_”、“-”和“.” 用作子分隔符的字符不应包含在捕获组中。

EX:子模式

20170408143311101_rdds.22;the-context=+39-20170408143311101@127.0.0.1-SET_PARAMETER.xml  

是:

date = 20170408143311101
type = rdds.22;the-context=+39-20170408143311101@127.0.0.1
attribute = SET_PARAMETER
ext = xml

现在我尝试了

^(?<date>\d{17})_(?<type>.*)-?(?<attribute>\w*)?\.?(?<ext>\w{3})?$
^(?<date>\d{17})_(?<type>.*)(-(?<attribute>\w*))?(\.(?<ext>\w{3}))?$

但在“类型”捕获组内折叠类型属性和扩展

什么时候

^(?<date>\d{17})_(?<type>.*)-(?<attribute>\w*)\.(?<ext>\w{3})$

不考虑选项

我如何改进表达式以在其捕获组中获取每个模式(如果存在)

我真的被困住了!

标签: phpregex

解决方案


试试看。我没有检查所有数据。

^(?<date>\d{17})_(?<type>.+?)(?:-(?<attribute>\w*))?(?:\.(?<ext>\w{3}))?$

推荐阅读