正则表达式接受命令并拆分命令、参数和参数值

Regex to take command and split up Command, Arguments, and Argument Values

下午好,

我觉得我在这个特定任务中有点不知所措。我正在尝试创建一个正则表达式匹配函数来输入命令,并将命令名称、参数和参数值拆分。

New-Variable -Name Something -Force 结果应该是

  1. 新变量
  2. -姓名
  3. 某事
  4. -力

到目前为止我已经想到了这个,但它只捕获了第一个参数集。

小贴士:有什么办法可以让所有匹配的命令都递增命名吗?说Parameter1、Value1、Parameter2、Value2等等?

^(?P<Command>[a-zA-Z]+-[a-zA-Z]+)(?: +)((-\S+)(?: |:|=)(.*){0,1})(?: +)

我什至不知道 PowerShell 解析器的存在,但这太棒了。这是我确定的代码。谢谢大家的帮助!

#Split up the command argument, needed to pull useful information from the command.
New-Variable -force -Name SplitCommand -Value ([System.array]$Null)
$null = [System.Management.Automation.Language.Parser]::ParseInput($Command, [ref]$SplitCommand,[ref]$Null)
$SplitCommand = $SplitCommand.where({-NOT [String]::IsNullOrEmpty($_.text)}).text

不要为此使用正则表达式 - 请改用内置解析器:

# Prepare command to parse
$command = 'New-Variable -Name Something -Force'

# Parse command invocation - Parser will return an Abstract Syntax Tree object
$parserErrors = @()
$AST = [System.Management.Automation.Language.Parser]::ParseInput($command, [ref]$null, [ref]$parserErrors)]

if($parserErrors){
    # error encountered while parsing script
}
else {
    # No errors, let's search the AST for the first command invocation
    $CommandInvocation = $AST.Find({ $args[0] -is [System.Management.Automation.Language.CommandAst] }, $false)

    # Get the string representation of each syntax element in the command invocation
    $elements = $CommandInvocation.CommandElements |ForEach-Object ToString
}

根据您的输入 (New-Variable -Name Something -Force),生成以下字符串:

PS ~> $elements
New-Variable
-Name
Something
-Force

注意:与:参数紧密绑定的参数将被解释为单个联合语法元素,例如。 'Get-Thing -Name:nameOfThing' 将只生成两个字符串(Get-Thing-Name:nameOfThing)——如果您希望将它们拆分为单独的字符串,请在将它们转换为字符串之前考虑到这一点:

$elements = $CommandInvocation.CommandElements |ForEach-Object {
  if($null -ne $_.Argument){
    # tightly bound argument, output both separately
    "-$($_.ParameterName)"
    $_.Argument
  } else {
    # just the parameter name, output as-is
    $_
  }
} |ForEach-Object ToString

用简化的解决方案补充,假设:

  • 您只是对 字符串数组 表示命令名称及其参数感兴趣。

  • 该字符串表示语法上有效的命令,即您不必担心错误处理。

$stringToParse = 'New-Variable -Name Something -Force'

$tokens = $null # Initialize the output variable.
# Parse the string as a PowerShell command.
$null = [System.Management.Automation.Language.Parser]::ParseInput(
  $stringToParse, 
  [ref] $tokens,  # will receive a collection of tokens
  [ref] $null     # would receive a collection of parsing errors; unused here
)

$tokenStrings = $tokens.Text -ne '' # -ne '' ignores the end-of-input token

$tokenStrings 然后包含一个字符串数组,其中包含逐字元素

New-Variable, -Name, Something, -Force.

另请参阅: