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

时间:2022-04-26 00:35:18

In PowerShell I find myself doing this kind of thing over and over again for matches:

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

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

So basically - run a command that generates lines of text, and for each line I want to run a command on a regex capture inside the line (if it matches). Seems really simple. The above works, but is there a shorter way to pull out those regex capture groups? Perl had $1 and so on, if I remember right. Posh has to have something similar, right? I've seen "$matches" references on SO but can't figure out what makes that get set.

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

I'm very new to PowerShell btw, just started learning.

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

3 个解决方案

#1


14  

You can use the -match operator to reformulate your command as:

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

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

#2


7  

Named Replacement

命名替换

'foo bar' -replace '(?<First>foo).+', '${First}'

Returns: foo

返回:foo

Unnamed Replacement

未命名的替换

 'foo bar' -replace '(foo).+(ar)', '$2 z$2 $1'

Returns: ar zar foo

返回:ar zar foo

#3


4  

You could try this:

你可以试试这个:

Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value } 

#1


14  

You can use the -match operator to reformulate your command as:

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

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

#2


7  

Named Replacement

命名替换

'foo bar' -replace '(?<First>foo).+', '${First}'

Returns: foo

返回:foo

Unnamed Replacement

未命名的替换

 'foo bar' -replace '(foo).+(ar)', '$2 z$2 $1'

Returns: ar zar foo

返回:ar zar foo

#3


4  

You could try this:

你可以试试这个:

Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value }