I want PowerShell to array everything that matches the regular expression.

Asked 1 years ago, Updated 1 years ago, 379 views

If the following conditions exist, I would like to include the contents of the matched parentheses in the array.
How do I achieve this with PowerShell?

conditions:

$data="{ab}, {cd}, {ef}..."#This length is variable rather than fixed
$regex='{ (.+?)}'

Expect Results:

$array[0]="ab" 
$array[1] = "bc" 
$array[2] = "ef" 

*Notes
PowerShell may not have the idea of putting it in an array, but
Once upon a time, Perl would have been easier to process if you put these things in an array.
PowerShell will do it.

regular-expression powershell

2022-12-30 19:06

2 Answers

Basically, it's just as Payaneco replied, but with a little more ingenuity in the regular expression, PowerShell will be able to access it easily.

$data="{ab}, {cd}, {ef}..."# This length is not fixed and is variable.
$regex='(?<={).+?(?=})'

$ms = [regex]::Matches($data,$regex)#The match can be retrieved as a collection at this time
$ms.Value#displaying

This is a feature called member access operator that automatically accesses members of each element when they access a member that does not exist.
That is, $ms is [Regex]::Matches(), where $ms.Value does not have the Value property in MatchCollection, so it functions as $ms|ForEach-Object{$_.Value}.

(According to Payaneco's answer, this feature can be used up to .Groups, but it becomes a member that exists as of [1], and the second element is retrieved.Therefore, regular expressions had to be devised to be accessible in .Value).

How should I put it in the array?

Run $ms.Value.GetType() to

PS>$ms.Value.GetType()

IsPublic IsSerial Name BaseType
-------- -------- ----                                     --------
True Object [ ] System.Array

$ms.Value is already an array so that you can get it.Place it where you want to store it.


2022-12-31 07:59

[regex]::Matches allows you to retrieve match results as a collection ( ) array).

sample code

$data="{ab}, {cd}, {ef}..."# This length is not fixed and is variable.
$regex='{ (.+?)}'

$ms = [regex]::Matches($data,$regex)#The match can be retrieved as a collection at this time
Collect strings in $array=($ms|%{$_.Groups[1].Value})#() as group values and put them in the $array variable
$array# display


2022-12-31 18:39

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.