是否有更短的方法将群组拉出Powershell正则表达式?

sco*_*obi 18 regex powershell

在PowerShell中,我发现自己一遍又一遍地为匹配做这种事情:

some-command | select-string '^(//[^#]*)' |
     %{some-other-command $_.matches[0].groups[1].value}
Run Code Online (Sandbox Code Playgroud)

所以基本上 - 运行一个生成文本行的命令,对于每一行,我想在行内的正则表达式捕获上运行命令(如果它匹配).看起来很简单.上面的工作,但有没有一个更短的方法来拉出这些正则表达式捕获组?Perl有1美元,依此类推,如果我没记错的话.辣妹必须有类似的东西,对吧?我在SO上看过"$ matches"引用,但无法弄清楚是什么让它得到了设置.

我对PowerShell btw很新,刚开始学习.

Bas*_*ink 14

您可以使用-match运算符重新配置您的命令:

some-command | Foreach-Object { if($_ -match '^(//[^#]*)') { some-other-command $($matches[1])}}
Run Code Online (Sandbox Code Playgroud)


小智 8

命名替换

'foo bar' -replace '(?<First>foo).+', '${First}'
Run Code Online (Sandbox Code Playgroud)

返回:foo

未命名的替换

 'foo bar' -replace '(foo).+(ar)', '$2 z$2 $1'
Run Code Online (Sandbox Code Playgroud)

返回:ar zar foo