none
Using regex get matching multiple strings from file RRS feed

  • Question

  • using regex and not foreach from powershell I want to match name and get all name ONLY in string array, the code is not working  

    $a=select-string -pattern "name:?(<name>))" c:\temp\main.txt| % {"$($_.matches.groups[1])"}
    echo $a

    $file=gc c:\temp\main.txt $regex='name: {0}' $file_content = [string]::Join("`r`n", $file); Select-String -InputObject $file_content -Pattern $regex -AllMatches

    --- apps: - name: my-app - route: dd - main: turbo - name: mean-app - route: dd - main: turbo - name: team-app - route: dd - main: turbo

    majorcon:

    - dbcon : tr

    - name: forth-app




    • Edited by Himanshu_Kulkarni Thursday, August 29, 2019 6:03 AM name key in bold, need value of this key for understanding purpose
    • Moved by Bill_Stewart Tuesday, November 19, 2019 7:18 PM Unanswerable
    Thursday, August 29, 2019 6:01 AM

All replies


  • Select-String -Path 'c:\temp\main.txt' -Pattern '(?<=name:\s+).*(?=$)' -AllMatches |
        Select-Object -ExpandProperty Matches |
            Select-Object -ExpandProperty Value
    It works for the given example text.

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    • Edited by BOfH-666 Thursday, August 29, 2019 7:32 AM
    Thursday, August 29, 2019 7:10 AM
  • You might not need the -AllMatches parameter if there is only one match per line as your string example suggests. So, you could also try:
    $pattern = "(?<=name:\s+).+$"
    (get-content .\regex_test1.txt | Select-String -Pattern $pattern | Select -ExpandProperty Matches).Value
    wizend
    Thursday, August 29, 2019 10:02 AM
  • You might not need the -AllMatches parameter if there is only one match per line as your string example suggests.
    Right. But what's defenitely unnecessary is the Get-Content in your example. You can provide a file for Select-String.  ;-)

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Thursday, August 29, 2019 11:07 AM