-2

I search for a regular expression to extract a Powershell param block from a complete PowerShell script.

[CmdletBinding()]
Param(
     [Parameter(Mandatory=$True,Position=1)]
     [string]$computerName,

     [Parameter(Mandatory=$True)]
     [string]$filePath
    )

...

A colleague means that it is not possible to parse this structure by using a regualr expression. He said regular expressions can't count the opening and closing signs (...) inside the param block and that makes it impossible to parse the param block.

k7s5a
  • 1,287
  • 10
  • 18
  • 1
    I'm sure its possible but it would be a complex regex with a lot of escaped characters. What have you tried and what output are you ultimately trying to achieve? – Mark Wragg Apr 19 '17 at 08:17
  • 3
    See [.NET regex reference](https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx#Anchor_3): you can use balancing group constructs. However the correct approach is to use AST parser ([example](http://stackoverflow.com/a/42548383/3959875)) – wOxxOm Apr 19 '17 at 08:17
  • 1
    Is there a particular reason _why_ you're even contemplating using regex here instead of just using PowerShell's parser? – Joey Apr 19 '17 at 08:51
  • I was recently contemplating the same thing (from the looks of your sample, pretty much the same thing really). But in the end I just decided to use another meta comment for that: `# param: computer, path` for each script. Much easier to extract, more flexibility elsewhere… – mario Apr 20 '17 at 22:36

1 Answers1

1

Good news: your colleague is wrong.
It is true that a simple regex has issues with nested data, but that is only true if you have unlimited level nesting.
This is explained very nicely in this question: How to match string within parentheses (nested) in Java?

In your case, even a simple regular expression can work:

(?:\[[^\]]+\]\s*)*\$\w+

Working example

This finds $parameters with blocks of [attributes] before them. There is very little nesting involved. This is a naive regex, and it fails if you have comments, strings with brackets, etc. But the regex can be expanded to support these cases.

Some more points:

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 1
    Your example doesn't cover default value of optional parameters – Clijsters Apr 19 '17 at 08:56
  • @Clijsters - Right! of course it doesn't, it is not meant to be a complete example. I did say "This is a naive regex, and it fails if you have comments, strings with brackets, etc. But the regex can be expanded to support these cases". This is a *theoretical* is-it-possible question, not a practical one. – Kobi Apr 19 '17 at 08:59