Is there a shorter way to pull groups out of a Powershell regex?

后端 未结 3 710
星月不相逢
星月不相逢 2020-12-30 03:09

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

some-command | select-string \'^(//[^#]*)\' |
     %{some-other-command         


        
相关标签:
3条回答
  • 2020-12-30 03:39

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

    some-command | Foreach-Object { if($_ -match '^(//[^#]*)') { some-other-command $($matches[1])}}
    
    0 讨论(0)
  • 2020-12-30 03:40

    You could try this:

    Get-Content foo.txt | foreach { some-othercommand [regex]::match($_,'^(//[^#]*)').value } 
    
    0 讨论(0)
  • 2020-12-30 03:54

    Named Replacement

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

    Returns: foo

    Unnamed Replacement

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

    Returns: ar zar foo

    0 讨论(0)
提交回复
热议问题