php - 带有捕获组的正则表达式
问题描述
我正在尝试将某些模式与正则表达式匹配,并且还能够捕获子模式(完整模式必须有效,应提取子模式。
我的一些模式是:
20170408143311101 _rdds.22; the-context=+39-20170408143311101@127.0.0.1-SET_PARAMETER。xml
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-TEARDOWN。xml
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_VARIABLE。xml
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})$
不考虑选项
我如何改进表达式以在其捕获组中获取每个模式(如果存在)
我真的被困住了!
解决方案
试试看。我没有检查所有数据。
^(?<date>\d{17})_(?<type>.+?)(?:-(?<attribute>\w*))?(?:\.(?<ext>\w{3}))?$
推荐阅读
- javascript - 如何在 Electron BrowserWindow 中打开 puppeteer 页面
- c# - 是否可以将 Unity GameObject 转换为 ScriptableObject 类类型?
- scala - 为什么 Scalavista 看不到 build.sbt 中设置的依赖项?
- c# - 获取列表项值
- javascript - 如何管理 CSS 框架以在我的 React 应用程序中仅使用一个组件
- java - 如何消除 GridBagLayout 中的空白?
- ios - swift 5 自定义单元格图片点击
- excel - 如何使用 Excel VBA 宏使 excel 工作表受保护和不受保护?
- python - 用布尔数组屏蔽opencv bgr的最有效方法
- flutter - Flutter 在现有项目中构建 Web 不断失败