Obtaining all placeholders from the @ {} pattern file using Powershell

advertisements

I am trying to get all the placeholders in a file which has a pattern @{}. I am trying to get hold of all variables but I am not able to define the pattern for the ending parentheses and also the whole word within. Below is my code so far

$SampleText = "I need all the variables with @{abc} @{def}
and @{xyz}"
$Pattern = '@{\w*'
$SampleText | Select-String -AllMatches -Pattern $Pattern
| Select-Object -ExpandProperty Matches | Select-Object -ExpandProperty Value

Doing this I am getting only @{abc, @{def and @{xyz as outputs. I need the whole @{abc}, @{def} and @{xyz} to be obtained. I tried changing the $pattern with lot of variations and it's not helping

Any help?


Here's a more succinct solution (PSv3+):

 $SampleText | % { [regex]::Matches($_, '@\{\w+\}').Value }

Note that even you though you got away without \-escaping { and } in your specific regex, you should generally do so, because they are metacharacters used in quantifiers (e.g., {2} to specify a repeat count of 2).

[regex] is PowerShell's type accelerator for type [System.Text.RegularExpressions.Match], which provides features beyond what the PowerShell's -match operator offers.

In this case, the static Matches method returns all matches of the specified regex in the input string, as [System.Text.RegularExpressions.Match] instances. Each such instance records the matched string in its .Value property, so applying .Value to the entire collection of matches (which is of type [System.Text.RegularExpressions.MatchCollection]), the individual matches are returned as an array of strings.