简体   繁体   中英

How to get multiple regex matches capture group

I am trying to access all matches of my first capture group ([^ ]+) in an array so I can foreach it, however I don't see it in the output:

$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

Yields:

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

Admittedly I have a lot to learn about the data structures and how to access them.

Before we get to the real answer, please consider renaming your variables - both $Matches and $Input are automatic and can be overwritten by the runtime .


In order to grab the value of the first capture group, you'll want to address index 1 in the Groups property or index 0 in the Captures property of each match:

$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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM