RegEx Pain

Welcome Forums General PowerShell Q&A RegEx Pain

This topic contains 4 replies, has 3 voices, and was last updated by

 
Participant
3 weeks, 6 days ago.

  • Author
    Posts
  • #112642

    Participant
    Points: 0
    Rank: Member

    Hi,

    Im trying to get the hash after the

    Commit:

    using RegEx and Select-String, but i can't get it to work – i'm hoping one of you guys can see where im going wrong?

    $RegEx = '/Commit:?.*/gm'
    Select-String -InputObject $StringOutput -Pattern $RegEx
    
    The value of $StingOutput is:
    Comments :
               +  : merge from develop
               
    Version  : 
               Commit: 2dfg444dfxbbghd6764ghb15ed8afd9f171
               Build Version: 3.0.981
    

    Thanks

    Tommy

  • #112643

    Participant
    Points: 19
    Rank: Member

    Multiline strings are always a bit tricky, especially because in PS they can come in two flavours — a single string, or many strings, one per line.

    I wouldn't use Select-String here, though, in general. It's good for finding the line your match exists on, but actually retrieving the match is a little trickier in some cases. I like to work with the built in -match operator.

    # If the string is one big block, split on newline
    $Lines = $StringOutput -split '\r\n?'
    $Lines | ForEach-Object {
        if ($_ -match 'Commit: (.+)') {
            $Matches[1]
        }
    }
  • #112648

    Participant
    Points: 65
    Published
    Rank: Member

    I think, splitting and foreach would not be required here.

    $StringOutput -Match 'Commit: (.+)'
    $Matches[1]
    
    • #112664

      Participant
      Points: 0
      Rank: Member

      Thanks for the replies.
      I ended up using Kvprasoon solution. I knew there would be a easier way. 🙂

      Cheers

      Tommy

  • #112688

    Participant
    Points: 65
    Published
    Rank: Member

    @TommyQuality : Power of community

You must be logged in to reply to this topic.