Remove text from variable

This topic contains 3 replies, has 3 voices, and was last updated by  taotao07 1 week, 4 days ago.

  • Author
    Posts
  • #81862

    taotao07
    Participant

    Hi there, here's what i'm trying to accomplish, I have the following:
    $t = "|one|two","|three|four","|one|four","|three|two"
    I'm trying to use regex to remove first portion in above values:
    $t -replace regexvalue | select-object -unique
    ...and I want to get
    two
    four
    I know it's possible, I just can't seem to get the regex syntax right.
    Thank you

  • #81868

    Curtis Smith
    Participant

    You can't do that directly on an array like you are doing there. RegEx works on a string. You have to loop through the array for each string and do the regex

    Using the Pipeline will do this automatically for you since it will send one element of the array down the pipeline at a time.

    $t = "|one|two","|three|four","|one|four","|three|two"
    $t |
    Select-String -Pattern "\|([^\|]+)$" |
    Select-Object -ExpandProperty Matches |
    ForEach-Object {
        $_.Groups[1].value
    } |
    Select-Object -Unique
  • #81892

    Christian Sandfeld
    Participant

    And if you don't want to deal with regex (assuming the value you want is always in the same position) you could do it with split like this:

    $t = "|one|two","|three|four","|one|four","|three|two"
    
    $t | 
    ForEach-Object {
        $_.Split('|')[2]
    } | 
    Select-Object -Unique
  • #81905

    taotao07
    Participant

    Wooohoooo, thank you both.

You must be logged in to reply to this topic.