I want to use PowerShell's Select-String cmdlet to find matching outermost parentheses. I've searched and found a regular expressions to do what I need and, although it works when I test it in https://regex101.com, I can't get it to work in PowerShell.
Here is an example that demonstrates what I am trying to do:
I want to find blocks of text where the outermost parentheses might contain any text including nested parentheses, might span multiple lines, and the opening outermost parenthesis is preceded by a certain word ("item" in this example). The text doesn't follow any particular structure.
Using the following block of text to demonstrate:
$myText = @' Here is some text spanning multiple lines with no particular structure. Some item ( (one_(two( three ) yadda yadda)) more text (xyz) blah ) the end. Blah blah ( stuff ( more)) and another item (single parens enclosing text). '@
I used the PowerShell Select-String cmdlet with my regex as follows:
$results = $myText | Select-String -Pattern 'item (\([^()]*(?:(?1)[^()]*)*\))' -AllMatches
The regex pattern
item (\([^()]*(?:(?1)[^()]*)*\))
produced an error in PowerShell so I changed the?1
back reference to\1
(based on .Net documentation about back referencing groups) and tried again. Changing the back reference to\1
eliminated the error but Select-String didn't work as I expected.I expected it to find the following two blocks of text:
Expected first match:
item ( (one_(two( three ) yadda yadda)) more text (xyz) blah )
Expected second match:
item (single parens enclosing text)
The PowerShell Select-String cmdlet finds only the block with the single set of parentheses (i.e. the expected second match shown above). It did not find blocks with the nested parentheses.
My regex finds both matches when tested in https://regex101.com, but does not work in PowerShell. I've searched and found a lot of information about regular expressions for finding nested parentheses, but nothing that tells me why this isn't working in PowerShell. I've also looked at the site https://www.regular-expressions.info/powershell.html, but I didn't see anything there that addresses the issue I am having.