regex - 如何获取多个正则表达式匹配捕获组
问题描述
我正在尝试访问([^ ]+)
数组中我的第一个捕获组的所有匹配项,以便我可以访问foreach
它,但是我在输出中看不到它:
$input = "Row 1:
Computer: xxx
Last Heartbeat: 4/9/2020 11:27:24 AM
Row 2:
Computer: yyy
Last Heartbeat: 4/9/2020 11:27:37 AM"
$matches = ([regex]'Computer: ([^ ]+)').Matches($input)
$matches
产量:
Groups : {0, 1}
Success : True
Name : 0
Captures : {0}
Index : 7
Length : 13
Value : Computer: xxx
Groups : {0, 1}
Success : True
Name : 0
Captures : {0}
Index : 66
Length : 13
Value : Computer: yyy
诚然,我有很多关于数据结构以及如何访问它们的知识。
解决方案
在我们得到真正的答案之前,请考虑重命名你的变量——两者$Matches
都是$Input
自动的,并且可以被运行时覆盖。
为了获取第一个捕获组的值,您需要处理属性中的索引 1或每个匹配项Groups
的属性中的索引 0 :Captures
$string = "Row 1:
Computer: xxx
Last Heartbeat: 4/9/2020 11:27:24 AM
Row 2:
Computer: yyy
Last Heartbeat: 4/9/2020 11:27:37 AM"
$results = ([regex]'Computer: ([^ ]+)').Matches($string)
$results | ForEach-Object { $_.Groups[1].Value }
# or
$results | ForEach-Object { $_.Captures[0].Value }
推荐阅读
- c# - I use syncfusion treeview and need to customize datatemplate in special way
- amazon-s3 - Python Cryptography 模块用于解密 s3 中的客户端加密数据
- typescript - 材质 UI 按钮移除焦点框
- css - 如何更改单个引导列的小屏幕上溢出/换行的方向?
- postgresql - 如何从 Diesel sql 函数中获取返回值
- javascript - Js写入类内部的文件方法
- javascript - Javascript按值查找嵌套对象
- python - 优先队列未在树中正确添加数据
- java - 测试 ArrayList .txt 文件的错误(不符合允许的格式)
- php - 如何组合三个表(MySQL)?